What this is
The three standard representations are the adjacency matrix, the adjacency list. And the edge list. Each trades space for speed on different operations.
Adjacency Matrix
A V×V grid where M[i][j] = 1 means an edge exists from i to j.
- Edge lookup is O(1) — one array access. Unbeatable.
- Space is O(V²) regardless of edge count. A graph with 10,000 vertices needs 100 million entries even if it has ten edges.
- Listing a vertex's neighbours costs O(V) — you must scan an entire row, mostly zeros.
For an undirected graph the matrix is symmetric, so half of it is redundant.
Adjacency List
An array of lists: each vertex stores only the neighbours it actually has.
- Space is O(V + E) — proportional to real edges, not possible ones.
- Iterating neighbours is O(degree) — exactly what BFS and DFS do at every step. This is why they use lists.
- Edge lookup is O(degree) — you scan the list rather than jumping to it.
Take four vertices A, B, C, D and edges A–B, A–C, C–D. The adjacency list stores A: [B, C], B: [A], C: [A, D], D: [C]. An undirected adjacency matrix records the same links in a 4×4 grid, with mirrored entries for each edge. The list stores only the six neighbor references; the matrix reserves all 16 cells.
The Rule of Thumb
Slide density and watch the two memory figures cross over.
- Sparse graphs (E &lll; V²) — use an adjacency list. Road networks, social graphs and web links are all sparse: most pairs are not connected.
- Dense graphs (E approaching V²) — a matrix becomes competitive on memory and wins outright on lookup speed.
Real-world graphs are by far sparse, which is why the adjacency list is the default in practice.
It Changes Algorithm Cost
This is not just a storage detail. BFS and DFS are O(V + E) with an adjacency list but O(V²) with a matrix, because each vertex must scan a whole row. On a sparse graph with a million vertices that is the difference between seconds and hours.
Similarly, Dijkstra is O(V²) with a matrix and simple scanning, but O((V+E) log V) with an adjacency list and a binary heap.
A Third Option: Edge List
Simply a list of (u, v, weight) triples. Terrible for asking "who are u's neighbours?" but ideal when an algorithm processes every edge in sorted order — which is exactly what Kruskal's MST algorithm does.
Experiments to try with Graph Representations
- Start at 30% density. The matrix is mostly zeros — every one of them still occupies memory.
- Switch to the adjacency list. The same graph, stored in a fraction of the space, with only real edges recorded.