Implement a Go graph using a map of integer slices to represent an adjacency list structure.
Use a map of slices to store nodes and their neighbors, where the key is the source node and the value is a slice of destination nodes.
package main
type Graph struct {
adj map[int][]int
}
func NewGraph() *Graph {
return &Graph{adj: make(map[int][]int)}
}
func (g *Graph) AddEdge(u, v int) {
g.adj[u] = append(g.adj[u], v)
}
func (g *Graph) Neighbors(u int) []int {
return g.adj[u]
}
An adjacency list is a way to store a graph where each node keeps a list of its direct connections. It is efficient for graphs with few connections because it only uses memory for edges that actually exist. Think of it like a contact list where each person has a list of friends, rather than a giant grid showing every possible relationship.