Chapter 65
HomeA graph is a set of nodes (vertices) connected by edges. The adjacency list stores for each node a list of its neighbours — the most common and flexible representation.
An array of vectors — adj[u] contains all neighbours of node u. For weighted graphs, store pairs of (neighbour, weight).
int n = 5; vector> adj(n); // unweighted // or: vector >> adj(n); // weighted // Add edge u↔v (undirected) adj[u].push_back(v); adj[v].push_back(u); // Add edge u→v (directed) adj[u].push_back(v); // Iterate neighbours for (int v : adj[u]) { /* ... */ }
let n = 5; let mut adj: Vec> = vec![vec![]; n]; adj[u].push(v); adj[v].push(u); for &v in &adj[u] { /* ... */ }
💡 O(V+E) memory — the gold standard
Adjacency list uses O(V+E) memory — proportional to actual edges. Sparse graphs (E ≈ V) use almost no memory. Always prefer this over adjacency matrix unless the graph is tiny and dense.
adj[u] = list of neighbours. O(V+E) memory.(neighbour, weight) tuples for weighted graphs.