Sub topic 9
Storing a graph as an adjacency matrix
This chapter assumes you know Python lists, dictionaries, and big-O notation. It also assumes you have read the chapter on adjacency lists, because the matrix is easiest to understand next to it.
The working model
An adjacency matrix is a square table with one row and one column per vertex. Cell matrix[i][j] answers one question: is there an edge from vertex i to vertex j? For an unweighted graph the cell holds 1 (edge) or 0 (no edge). For a weighted graph it holds the weight, and a marker value means "no edge".
Python lists are indexed by integers, so you first map each vertex name to a row number.
def build_matrix(vertices, edges, directed=False, absent=0):
index = {v: i for i, v in enumerate(vertices)}
n = len(vertices)
matrix = [[absent] * n for _ in range(n)]
for edge in edges:
u, v = edge[0], edge[1]
weight = edge[2] if len(edge) > 2 else 1
matrix[index[u]][index[v]] = weight
if not directed:
matrix[index[v]][index[u]] = weight
return matrix, index
names = ["A", "B", "C"]
undirected, _ = build_matrix(names, [("A", "B"), ("B", "C")])
directed, _ = build_matrix(names, [("A", "B"), ("B", "C")], directed=True)
weighted, _ = build_matrix(
names, [("A", "B", 4), ("A", "C", 1), ("C", "B", 2)], absent=None
)
print(undirected) # [[0, 1, 0], [1, 0, 1], [0, 1, 0]]
print(directed) # [[0, 1, 0], [0, 0, 1], [0, 0, 0]]
print(weighted) # [[None, 4, 1], [4, None, 2], [1, 2, None]]The three graph types differ only in how you fill the table.
- Undirected: each edge sets two cells,
[i][j]and[j][i]. The matrix is symmetric across its diagonal. - Directed: each edge sets one cell. Row is the tail (where the edge starts) and column is the head (where it ends).
- Weighted: the cell holds the weight. Pick an
absentmarker that cannot be a real weight. Weight 0 can be legitimate, soNoneorfloat("inf")is safer than 0.
Reading degrees from the matrix
Row i lists the edges leaving vertex i. Column i lists the edges arriving at it. This gives a symmetric cost for the two directed degrees, unlike the adjacency list, where in-degree needed a scan of the whole graph.
def out_degree(matrix, i, absent=0):
return sum(1 for cell in matrix[i] if cell != absent)
def in_degree(matrix, j, absent=0):
return sum(1 for row in matrix if row[j] != absent)
print(out_degree(directed, 0)) # 1
print(in_degree(directed, 1)) # 1
print(in_degree(directed, 0)) # 0Both functions cost O(V), since each reads one row or one column.
Costs
| Operation | Adjacency matrix |
|---|---|
| Space | O(V²) |
| Is there an edge u to v? | O(1) |
| List neighbors of u | O(V) |
| Visit every edge | O(V²) |
The O(1) edge lookup is the main benefit. The O(V²) space is the main cost, and it is paid even when the graph has few edges.
Common errors
- Forgetting the mirror write. In an undirected graph, setting only
[i][j]creates a half-edge. Degree and traversal results then depend on which row you read. - Using 0 as "no edge" in a weighted graph. A real edge of weight 0 becomes invisible.
- Treating the diagonal carelessly.
matrix[i][i]is a self-loop. Shortest-path code often sets it to 0 as a distance, which differs from "the edge exists". - Indexing with vertex names. Lists need integers. Always go through the
indexdictionary, and keep it with the matrix.
Exercise
A directed graph has 1,000 vertices and 2,000 edges. How many cells does its adjacency matrix store, and how many of them represent edges?
Show answer
The matrix stores 1,000 × 1,000 = 1,000,000 cells. Only 2,000 of them represent edges, because each directed edge sets one cell. The other 998,000 hold the "no edge" marker.