Sub topic 2
Adjacency lists and matrices
This chapter assumes you know Python lists, dictionaries, and sets, and that you know what vertices and edges are. It covers the two standard ways to store a graph in memory when you write the edges down explicitly. Later chapters build graphs on demand instead, but the same questions apply: what are the neighbours of this vertex, and is there an edge between these two?
The example graph
The graph below has four vertices and four undirected edges.
Adjacency list
An adjacency list stores, for each vertex, the collection of its neighbours. In Python this is usually a dictionary that maps each vertex to a list.
from collections import defaultdict
edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")]
adj = defaultdict(list)
for u, v in edges:
adj[u].append(v)
adj[v].append(u) # drop this line for a directed graph
print(dict(adj))
print(adj["A"])The output is:
{'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'D'], 'D': ['B', 'C']}
['B', 'C']Listing the neighbours of a vertex costs time proportional to its degree, which is the number of edges at that vertex. The whole structure takes space proportional to V + E, where V is the number of vertices and E the number of edges.
Adjacency matrix
An adjacency matrix is a V × V table. Entry m[i][j] says whether an edge runs from vertex i to vertex j. Rows and columns are integers, so you first need to give each vertex an index.
vertices = ["A", "B", "C", "D"]
index = {name: i for i, name in enumerate(vertices)}
n = len(vertices)
matrix = [[0] * n for _ in range(n)]
for u, v in edges:
i, j = index[u], index[v]
matrix[i][j] = 1
matrix[j][i] = 1 # symmetric because the graph is undirected
for row in matrix:
print(row)
print(matrix[index["A"]][index["D"]])The output is:
[0, 1, 1, 0]
[1, 0, 0, 1]
[1, 0, 0, 1]
[0, 1, 1, 0]
0Checking for a single edge is one lookup. The cost is space: V² entries, even when most are zero.
Direction and weights
Direction and weight change how you fill each structure.
- Direction: add only
adj[u].append(v)and set onlymatrix[i][j]. The matrix is then no longer symmetric. - Weights: store pairs
(v, weight)in the list, or put the weight in the matrix cell. With a matrix, useNoneor infinity for "no edge", because 0 can be a legitimate weight.
Comparing the two
| Question | Adjacency list | Adjacency matrix |
|---|---|---|
| Space | V + E | V² |
| Is there an edge u → v? | Scan u's neighbours | One lookup |
| List neighbours of u | Proportional to degree | Scan a row of length V |
| Best for | Sparse graphs | Dense graphs, small V |
A graph is sparse when E is far smaller than V², and dense when E is close to V². Most graphs in this tutorial are sparse. A grid cell has at most 4 or 8 neighbours, however large the grid is. A matrix for a 1000 × 1000 grid would need 10¹² entries for only about four million edges. For that reason, adjacency lists are the default choice here.
Even an adjacency list can be unnecessary. When the neighbours follow a rule, as in a grid, you can compute them when asked and store nothing. The next chapters build on that idea.
Exercise
A directed graph has 5,000 vertices and 20,000 edges. Which structure would you pick, and roughly how many entries would the matrix hold compared with the list?
Show answer
Use an adjacency list. The matrix would hold 5,000 × 5,000 = 25 million entries, while the list holds about 5,000 + 20,000 = 25,000 items. The graph is sparse, since 20,000 is far below 25 million.