Adjacency list or adjacency matrix
1 Signposts or a chart
The last lesson's city map came the way a problem gives it: n = 7 and a list of six roads.
A search, such as BFS or DFS in the next lesson, asks one question at every junction: where can I go from here? With only the edge list, each answer means reading all E roads. At V = 10⁵ and E = 2 × 10⁵, that is around 2 × 10¹⁰ steps. At about 10⁸ steps a second, it gets Time Limit Exceeded (TLE).
So we first copy the graph into a form that answers fast. Road maps use two:
- A distance chart, as at the back of a road atlas. It has a row and a column for every town.
- A signpost at each junction. It lists only where this junction's roads lead.
The chart is the adjacency matrix, and the signposts are the adjacency list.
2 The adjacency matrix: a chart of every pair
The adjacency matrix is a V × V table called matrix. The cell matrix[u][v] is 1 when a road joins u and v, and 0 when none does. Here it is for our map, with the vertex numbers along the top and down the side:
Each road is written twice, at matrix[u][v] and at matrix[v][u]. So the table is a mirror image across its diagonal.
The chart is quick for one kind of question. Is there a road between 3 and 4? We read one cell, matrix[3][4], in O(1).
It is slow for the search's question. To find where 1's roads lead, we read all of row 1: seven cells, to find three 1s. And most of the chart is empty. Of its 49 cells, only 12 hold a 1, but the 37 zeros take memory too.
3 The adjacency list: a signpost at each vertex
The adjacency list gives each vertex a list of its neighbours and nothing else. In code, it is an array of V lists called adj, and adj[u] is the signpost at junction u:
Now the search's question is cheap. To find where 1's roads lead, we read adj[1]: three numbers, with no zeros to skip. The time is the vertex's degree.
The lists hold 12 numbers in all, because each road is on the signposts at both its ends. That is the handshake lemma from the last lesson: the degrees add up to 2E. So the lists take V + 2E places, which is O(V + E).
The chart's quick question is slower here. To check for a road between 3 and 4, we search adj[3] for 4, in up to degree(3) steps.
The order inside a list does not matter. It follows the edge list, which is why adj[2] reads 1, 0.
4 Building the list from an edge list
We make V empty lists, then read the edges once. For each edge [u, v], v goes into u's list and u goes into v's list. We add both, because the road goes both ways.
Each edge did two appends, and each append is O(1). So building the list takes O(V + E) time. The matrix is built by the same loop, which writes 1 into two cells instead of appending. Here are both:
C++
n empty lists in one line. vector<vector<int>> adj(n) makes n empty vectors. Pass adj to a helper by reference, as vector<vector<int>>&. Passing it by value copies all V + 2E numbers on every call.
One new ArrayList<>() per vertex. The loop gives each vertex its own list. An array of lists is also common, but Java cannot make an array of a generic type: new ArrayList<Integer>[n] is a Compile Error. List<Integer>[] adj = new ArrayList[n] compiles with a warning, and each place still needs its own new ArrayList<>().
Use the comprehension. [[] for _ in range(n)] makes n separate lists. [[]] * n makes n names for one list, so every vertex shares one signpost. The matrix has the same trap: [[0] * n] * n makes n names for one row.
Use Array.from with a function. It calls () => [] once per place, so each vertex gets its own array. new Array(n).fill([]) puts one array in every place, so every vertex shares one signpost.
No inner make for the lists. make([][]int, n) gives n nil slices, and append works on a nil slice. The matrix is different: each row needs its own make, or writing to it panics.
Store neighbours as usize. The edges arrive as i32, so as usize converts each end once. The lists then hold usize, and later code can index adj with a neighbour directly. vec![Vec::new(); n] clones the empty vector n times, so each vertex gets its own list.
Make each list. new List<int>[n] is an array of n nulls, not n lists. Without the loop, the first Add throws a NullReferenceException, a Runtime Error. int[,] is one block of n × n cells, read as matrix[u, v].
For our map, printing each list and then each row of the matrix gives:
0: 1 2
1: 0 2 3
2: 1 0
3: 1 4
4: 3
5: 6
6: 5
0 1 1 0 0 0 0
1 0 1 1 0 0 0
1 1 0 0 0 0 0
0 1 0 0 1 0 0
0 0 0 1 0 0 0
0 0 0 0 0 0 1
0 0 0 0 0 1 0
A directed graph has one-way roads. An edge [u, v] then goes from u to v only, so we drop the second line: adj[u] gets v, and adj[v] gets nothing. In the matrix, only matrix[u][v] becomes 1, so the chart is no longer a mirror image.
5 Road lengths: weighted graphs
In a weighted graph, each road has a length, and a signpost says how far: "2, 1 km". Each entry in a list becomes a pair (neighbour, weight), held in a pair<int, int>:
for each edge (u, v, w)
adj[u].add((v, w))
adj[v].add((u, w))
Here are the last lesson's road lengths, on the signposts:
In the matrix, a cell holds the road's length instead of 1. Then "no road" needs a value that no road can have. A 0 works only while every length is above 0. When a weight can be 0, such as the toll on a free road, a 0 cell reads as no road at all. Then "no road" must be a very large number standing for ∞, where a distance chart leaves a dash.
6 What each one costs
The two forms trade speed on different questions:
| Job | Matrix | List |
|---|---|---|
| Space | O(V²) | O(V + E) |
| Is there a road u–v? | O(1) | O(degree of u) |
| All neighbours of u | O(V) | O(degree of u) |
| Every neighbour of every vertex | O(V²) | O(V + E) |
| Build from the edge list | O(V²) | O(V + E) |
The last two rows decide most problems. A search visits every vertex and reads every neighbour. With a matrix, each vertex reads a whole row of V cells, so the search costs O(V²) however few roads there are. With lists, it reads only real roads, and the degrees add up to 2E.
The space row decides the rest. A typical problem has V = 10⁵ and E = 2 × 10⁵:
- Matrix. It has 10¹⁰ cells. Even at one byte a cell, that is about 10 GB, far more memory than any problem allows. The program fails before it reads the first edge.
- List. V + 2E is about 5 × 10⁵ numbers, a few MB.
At V = 1,000, the matrix has 10⁶ cells, which fits easily.
7 Mistakes
- Adding one direction only. If the loop skips
adj[v].add(u), the edge[1, 3]puts 3 into list 1 but not 1 into list 3. List 3 holds only 4, and list 4 is empty. A search from 3 reaches 4 and stops, though a road joins 3 and 1. - Vertices numbered from 1. With junctions 1 to 7, the edge
[6, 7]writes toadj[7], past the end of seven lists. That is a Runtime Error. Make n + 1 lists and leave list 0 empty. - Every vertex sharing one list. In Python and JavaScript, the short way to make n lists makes n names for one list. On our map, every signpost then reads all 12 entries,
1 0 2 1 0 2 3 1 4 3 6 5. The notes under the code show the safe way. - A matrix for a big graph. A matrix at V = 10⁵ runs out of memory before the search starts. Check V in the constraints before choosing it.
8 Which one to use
- The adjacency list: by default. Most problem graphs are sparse, and BFS, DFS and shortest paths all ask for a vertex's neighbours. Keys and Rooms and All Paths From Source to Target hand it over ready-made, as
rooms[i]andgraph[i]. - The adjacency matrix: small or dense graphs. It fits when V is up to about 1,000 and the code often asks whether u and v are joined. Number of Provinces gives its graph as a matrix, and Floyd-Warshall, in a later lesson, works on one.
- The edge list as it is. Some algorithms look at roads, not neighbours. Kruskal's algorithm, in a later lesson, sorts the edges by weight and needs nothing else.
- A grid: nothing to build. A cell's neighbours are one step up, down, left or right, so the code calculates them when it needs them:
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for each (dr, dc) in directions
nr = r + dr
nc = c + dc
if 0 <= nr < rows and 0 <= nc < cols
(nr, nc) is a neighbour of (r, c)
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.