Sub topic 9
Storing a graph as an adjacency matrix
This chapter assumes you can read Python lists of lists, know big-O notation, and have met the adjacency list from the previous chapter. It shows how to store a graph in a square table, how that table changes for undirected, directed, and weighted graphs, and which mistakes to avoid when you build one.
The idea: one cell per ordered pair
An adjacency matrix is a square table with one row and one column for every vertex. The cell at row i, column j answers one question: is there an edge from vertex i to vertex j?
For a graph with V vertices the matrix has V × V cells, however few edges the graph has. Cells are addressed by integer position, so each vertex needs an index from 0 to V − 1. Vertex names such as "A" or "Paris" need a lookup table that maps each name to its index.
The graph below is directed and has three edges. Its matrix follows the diagram.
| from \ to | A | B | C |
|---|---|---|---|
| A | 0 | 1 | 1 |
| B | 0 | 0 | 1 |
| C | 0 | 0 | 0 |
Read a row as "edges leaving this vertex" and a column as "edges arriving at this vertex". That reading is the basis of most matrix algorithms.
Building a matrix in Python
The helper below creates the index map and an empty matrix. It builds each row separately. Section "Common errors" explains why.
def make_matrix(vertices, fill=0):
index = {v: i for i, v in enumerate(vertices)}
n = len(vertices)
matrix = [[fill] * n for _ in range(n)]
return index, matrix
def add_matrix_edge(index, matrix, u, v, weight=1, directed=False):
matrix[index[u]][index[v]] = weight
if not directed:
matrix[index[v]][index[u]] = weight
vertices = ["A", "B", "C"]
idx, undirected = make_matrix(vertices)
add_matrix_edge(idx, undirected, "A", "B")
add_matrix_edge(idx, undirected, "B", "C")
idx, directed = make_matrix(vertices)
add_matrix_edge(idx, directed, "A", "B", directed=True)
add_matrix_edge(idx, directed, "B", "C", directed=True)
print(undirected) # [[0, 1, 0], [1, 0, 1], [0, 1, 0]]
print(directed) # [[0, 1, 0], [0, 0, 1], [0, 0, 0]]How each graph type shows up
Undirected graphs are symmetric
An undirected edge between A and B is stored twice, at [A][B] and at [B][A]. The matrix therefore equals its own transpose (the table flipped across its diagonal). You can use this to validate input: if matrix[i][j] != matrix[j][i] anywhere, the data is not a valid undirected graph.
The symmetry means that half the table repeats the other half. Some programs store only the upper triangle to save space. That halves the memory, but every lookup must then order its two indices first.
Directed graphs are not symmetric
A directed edge from A to B sets only [A][B]. The reverse cell stays empty unless the graph also has an edge from B to A. In the directed matrix above, the edge A → B is present and the cell [B][A] is 0.
Weighted graphs store the weight in the cell
A weighted graph puts the weight in the cell in place of a 1. This creates a problem: you need a value that means "no edge", and it must not be a legal weight. Zero is a poor choice, because an edge can legitimately have weight 0. A common alternative is positive infinity for "no edge" and 0 on the diagonal, because a vertex is at distance 0 from itself.
INF = float("inf")
idx, weighted = make_matrix(["A", "B", "C"], fill=INF)
for i in range(3):
weighted[i][i] = 0
add_matrix_edge(idx, weighted, "A", "B", 4)
add_matrix_edge(idx, weighted, "A", "C", 1)
add_matrix_edge(idx, weighted, "C", "B", 2)
for row in weighted:
print(row)
# [0, 4, 1]
# [4, 0, 2]
# [1, 2, 0]This graph is the same weighted graph used with the adjacency list. Here all three pairs are connected, so no inf appears in the output. Remove one edge and an inf will take its place.
Another option is None as the "no edge" marker. It is clearer to read, but it makes arithmetic fail with a TypeError, whereas inf works in comparisons and sums.
Operations on the matrix
Edge lookup is constant time
Checking whether an edge exists is a single index operation:
def has_edge(index, matrix, u, v, no_edge=0):
return matrix[index[u]][index[v]] != no_edge
print(has_edge(idx, weighted, "A", "B", no_edge=INF)) # TrueThis is the matrix's main advantage over the adjacency list, where the same check scans a neighbor collection (or hashes into it, if the neighbors are stored in a dictionary).
Finding neighbors takes time proportional to V
To list the neighbors of a vertex, you scan its entire row, even if it has one neighbor:
def neighbors(vertices, index, matrix, u, no_edge=0):
row = matrix[index[u]]
return [vertices[j] for j, cell in enumerate(row) if cell != no_edge]
idx, g = make_matrix(vertices)
add_matrix_edge(idx, g, "A", "B", directed=True)
add_matrix_edge(idx, g, "A", "C", directed=True)
print(neighbors(vertices, idx, g, "A")) # ['B', 'C']Traversals such as breadth-first search call this operation once per vertex. On a matrix, a full traversal therefore costs O(V²) in total, where an adjacency list costs O(V + E).
Degree comes from rows and columns
In a directed graph, out-degree is the number of filled cells in a row. In-degree is the number of filled cells in a column. Both are simple scans:
def out_degree(index, matrix, u, no_edge=0):
return sum(1 for cell in matrix[index[u]] if cell != no_edge)
def in_degree(index, matrix, u, no_edge=0):
j = index[u]
return sum(1 for row in matrix if row[j] != no_edge)
idx, g = make_matrix(vertices)
add_matrix_edge(idx, g, "A", "B", directed=True)
add_matrix_edge(idx, g, "C", "B", directed=True)
print(out_degree(idx, g, "A")) # 1
print(in_degree(idx, g, "B")) # 2Both cost O(V). With adjacency lists, out-degree is O(1) but in-degree needs a scan of the whole graph. The matrix treats the two directions evenly.
In an undirected 0/1 matrix, the degree of a vertex is its row sum, which equals its column sum. The sum of every cell is 2E, since each edge is stored twice. In a directed 0/1 matrix, the sum of every cell is E.
Adding and removing edges is cheap, adding vertices is not
Setting a cell to a value or back to "no edge" is O(1). Adding a vertex means adding a row and a column, and in a fixed-size structure that means rebuilding the whole table. For graphs whose vertex set changes often, this is a cost to plan for.
Memory cost
The matrix needs V² cells regardless of E. For 10,000 vertices that is 100 million cells. A Python list of lists holds a pointer in each cell, about 8 bytes on a 64-bit build, so this matrix needs roughly 800 MB before counting the objects it points to. A road network with 10,000 intersections might have only 30,000 edges, so almost every cell would be empty.
Matrices pay off on dense graphs, where E is close to V². They also pay off when V is small enough that the table fits easily and constant-time edge lookup matters. Libraries such as NumPy store the cells as packed numbers, which reduces the per-cell size to 1 to 8 bytes, but the V² growth stays. The next chapter compares the two representations directly.
Common errors
- Sharing rows by accident. Writing
[[0] * n] * ncreatesnreferences to one row. Setting one cell changes the same column in every row. Build each row separately, asmake_matrixdoes. - Using 0 as "no edge" in a weighted graph. An edge with weight 0 becomes invisible. Use
inforNone, and pass the same marker to every function that tests for edges. - Forgetting the second write on an undirected edge. If only
[u][v]is set, the graph behaves as directed. Keep both writes in one helper so they cannot drift apart. - Mixing up row and column. Row is the source and column is the target. Reversing them silently transposes the graph, which swaps in-degree and out-degree.
- Mishandling self-loops. A self-loop sets a diagonal cell. By convention an undirected self-loop adds 2 to the vertex's degree, but a row sum counts the diagonal cell once. Adjust for it if your graph can contain loops.
- Treating vertex names as indices. Keep the name-to-index dictionary with the matrix, and convert at the boundary of your functions.
Exercise
A weighted, directed graph is stored as a matrix that uses 0 for "no edge". A road from X to Y has a toll of 0. What goes wrong, and how do you fix it?
Show answer
The toll-free road looks identical to a missing road, so has_edge, neighbors, and both degree functions skip it, and any search will treat Y as unreachable from X. Fix it by choosing a "no edge" marker that is not a valid weight, such as float("inf") or None, filling the matrix with it, and passing that marker to every function that tests for edges.
Exercise
An undirected graph with 5 vertices and 6 edges is stored as a 0/1 matrix with no self-loops. What is the sum of all 25 cells, and what is the sum of the row for a vertex of degree 3?
Show answer
The total is 12, because each of the 6 edges is stored in two cells. The row sum for a vertex of degree 3 is 3, since it has three filled cells.