Sub topic 8
Representation 2: the adjacency matrix
This chapter assumes you know Python lists and dictionaries, introductory Big-O notation, and how a graph is described with vertices and edges. The previous chapter stored a graph as an edge list. Here you store the same graph as a table.
The idea
An adjacency matrix is an n-by-n table for a graph with n vertices. Entry [i][j] says whether an edge joins vertex i to vertex j. Rows are edge sources and columns are edge targets. A value of 1 means an edge exists and 0 means it does not.
Matrices are indexed by integers, but vertex names are often strings. So you first assign each vertex a position, then fill the table.
Building a matrix
edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")]
nodes = ["A", "B", "C", "D"]
index = {name: i for i, name in enumerate(nodes)}
n = len(nodes)
matrix = [[0] * n for _ in range(n)]
for u, v in edges:
matrix[index[u]][index[v]] = 1
matrix[index[v]][index[u]] = 1 # symmetric for an undirected graph
print(matrix[index["A"]][index["B"]]) # 1
print(matrix[index["A"]][index["D"]]) # 0The resulting table looks like this:
| Row | A | B | C | D |
|---|---|---|---|---|
| A | 0 | 1 | 1 | 0 |
| B | 1 | 0 | 0 | 1 |
| C | 1 | 0 | 0 | 1 |
| D | 0 | 1 | 1 | 0 |
For an undirected graph the table is symmetric: the entry at [i][j] always equals the entry at [j][i]. That is why the code writes both directions. For a directed graph you write only matrix[index[u]][index[v]] = 1, and the table is usually not symmetric.
What it costs
The matrix always holds n × n entries, no matter how many edges exist.
- Space: O(n²). A graph with 10,000 vertices needs 100 million entries, even if it has only 20,000 edges.
- Edge lookup: O(1). To test for an edge, read one cell. The edge list needed a linear scan.
- Neighbor iteration: O(n). To find the neighbors of a vertex, scan its whole row, even if it has only two neighbors.
- Adding or removing an edge: O(1). Change one cell (two cells if undirected).
- Adding a vertex: O(n²) in the worst case, because the table must grow in both dimensions.
Common errors
- Forgetting symmetry. On an undirected graph, writing only one direction makes lookups give different answers depending on argument order.
- Counting edges wrongly. Summing every entry in an undirected matrix counts each edge twice. Divide by 2 (a self-loop sits on the diagonal and needs separate handling).
- Reading a diagonal entry as a mistake.
matrix[i][i]is 1 only if vertexihas a self-loop. For simple graphs the diagonal is all zeros. - Using it for sparse graphs. A sparse graph has few edges compared with n². Most of the table is then zeros, and you pay for them in memory and in row scans.
When it fits
Use a matrix when the graph is dense, meaning the edge count is close to n². It also fits when the vertex count is small and you test for specific edges often. Both cases make the O(1) lookup worth the O(n²) space. The next chapter shows a structure that avoids the wasted zeros.
Exercise
A directed graph has 1,000 vertices and 3,000 edges. How many entries does its adjacency matrix hold, and what fraction of them are 1? How long does it take to list all out-neighbors of one vertex?
Show answer
The matrix holds 1,000 × 1,000 = 1,000,000 entries. Only 3,000 are 1 (a directed edge sets one cell), so 0.3% of the table is used. Listing the out-neighbors of one vertex means scanning its row of 1,000 cells, which is O(n), regardless of how many neighbors it has.
Exercise
You build an undirected graph's matrix but only set matrix[index[u]][index[v]] = 1 for each edge (u, v). With the edge ("A", "B"), what does matrix[index["B"]][index["A"]] return, and how do you fix the code?
Show answer
It returns 0, so the graph wrongly looks directed. Fix it by also setting matrix[index[v]][index[u]] = 1 inside the loop.