Sub topic 10
Adjacency list or matrix: choosing between them
This chapter assumes you can read Python dictionaries and lists, use big-O notation, and already know how an adjacency list and an adjacency matrix store a graph. Here, V is the number of vertices and E is the number of edges.
Same graph, two layouts
Both layouts describe the same graph. The list stores only the edges that exist. The matrix reserves a cell for every possible pair of vertices.
edges = [("A", "B", 4), ("A", "C", 1), ("C", "B", 2)]
names = ["A", "B", "C"]
index = {name: i for i, name in enumerate(names)}
adj_list = {name: {} for name in names}
matrix = [[None] * len(names) for _ in names]
for u, v, w in edges:
adj_list[u][v] = w
adj_list[v][u] = w
matrix[index[u]][index[v]] = w
matrix[index[v]][index[u]] = w
def has_edge_list(g, u, v):
return v in g[u]
def has_edge_matrix(m, u, v):
return m[index[u]][index[v]] is not None
def neighbors_list(g, u):
return list(g[u])
def neighbors_matrix(m, u):
return [names[j] for j, w in enumerate(m[index[u]]) if w is not None]
print(has_edge_list(adj_list, "A", "B")) # True
print(has_edge_matrix(matrix, "A", "B")) # True
print(neighbors_list(adj_list, "A")) # ['B', 'C']
print(neighbors_matrix(matrix, "A")) # ['B', 'C']The matrix uses None for "no edge" instead of 0, because 0 can be a valid weight.
Cost comparison
| Operation | Adjacency list (dict of dicts) | Adjacency matrix |
|---|---|---|
| Space | O(V + E) | O(V²) |
| Is there an edge u to v? | O(1) on average | O(1) |
| List the neighbors of u | O(out-degree of u) | O(V) |
| Add or remove one edge | O(1) on average | O(1) |
| In-degree of u (directed) | O(V + E) | O(V) |
| Full BFS | O(V + E) | O(V²) |
The two layouts differ in two ways. Finding the neighbors of a vertex costs far less in the list, because the matrix must scan a whole row, including the empty cells. Space is the other difference. A list stored as a dictionary grows with the edges that exist, and a matrix always grows with V².
Deciding
The deciding quantity is density, the number of edges compared to the maximum possible. A graph with about V² edges is dense. A graph with about V edges is sparse.
Most real graphs are sparse. A road network has a few roads per intersection, and a social network has a few hundred friends per person out of millions of people. A matrix for a million vertices would need a trillion cells, which does not fit in memory. For these graphs, use an adjacency list.
A matrix is a good choice when:
- V is small, up to a few thousand.
- The graph is dense.
- Your algorithm asks "is there an edge between u and v?" constantly, or works on whole rows at once.
Both traversal and Dijkstra's algorithm spend their time iterating over neighbors. That is why the list is the default for them.
Common errors
- Using a matrix for a large sparse graph and running out of memory.
- Storing an undirected edge in only one direction. Lookups then depend on the argument order.
- Using 0 to mean "no edge" in a weighted matrix when 0 is a legal weight.
- Assuming in-degree is cheap in a directed list. It needs a scan of every vertex.
Exercise
A directed graph has 10,000 vertices and about 30,000 edges. Which representation should you use for BFS, and roughly how many cells would a matrix need?
Show answer
Use an adjacency list. The graph is sparse (3 edges per vertex on average), so BFS costs O(V + E), about 40,000 steps. A matrix needs 10,000 × 10,000 = 100 million cells, and BFS on it costs O(V²).
Exercise
Why does the in-degree of a vertex cost O(V) in a matrix but O(V + E) in a dictionary-based adjacency list?
Show answer
In a matrix you scan one column of V cells. In the list you must check every vertex's neighbor dictionary, which touches all V vertices and, in the worst case, all E edges.