Sub topic 15
Representing graphs: adjacency list versus matrix
This chapter assumes you know basic graph terms (vertex, edge, directed, weighted, degree), Big-O notation, and Python lists. Every later algorithm in this tutorial, including BFS, Kruskal, Dijkstra and Floyd-Warshall, runs on one of the two representations below. Its stated running time depends on which one you pick.
Let V be the number of vertices and E the number of edges. Vertices are numbered 0 to V-1.
The two representations
An adjacency matrix is a V x V table mat. For an unweighted graph, mat[u][v] is 1 if the edge u→v exists and 0 otherwise. For a weighted graph, it holds the edge weight. A missing edge needs a sentinel value, usually infinity. A weight of 0 can be a legitimate edge weight, so 0 is a poor sentinel for weighted graphs.
An adjacency list is an array of V lists. The list at index u holds every neighbour v of u, and for a weighted graph each entry is a pair (v, w).
Both structures can be built from an edge list:
INF = float('inf')
def build_list(n, edges, directed=False):
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
if not directed:
adj[v].append((u, w))
return adj
def build_matrix(n, edges, directed=False):
mat = [[INF] * n for _ in range(n)]
for i in range(n):
mat[i][i] = 0
for u, v, w in edges:
mat[u][v] = w
if not directed:
mat[v][u] = w
return mat
edges = [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 5)]
adj = build_list(4, edges)
mat = build_matrix(4, edges)
print(adj)
print(mat[2][1], mat[0][3])
print(sum(len(nbrs) for nbrs in adj) // 2)The program prints [[(1, 4), (2, 1)], [(0, 4), (2, 2), (3, 5)], [(0, 1), (1, 2)], [(1, 5)]], then 2 inf, then 4. The last number counts each undirected edge twice in the list and divides by 2.
Setting the diagonal to 0 matches what Floyd-Warshall expects: the distance from a vertex to itself is 0.
Cost of each operation
| Operation | Adjacency list | Adjacency matrix |
|---|---|---|
| Space | O(V + E) | O(V^2) |
| Is there an edge u→v? | O(deg(u)) | O(1) |
| Visit all neighbours of u | O(deg(u)) | O(V) |
| Add an edge | O(1) | O(1) |
| Remove an edge | O(deg(u)) | O(1) |
| Degree of u | O(1) if you use the list length | O(V) |
| List all edges | O(V + E) | O(V^2) |
| Full BFS or DFS | O(V + E) | O(V^2) |
The traversal rows follow from the neighbour-scan row. A traversal scans the neighbours of each vertex once. Over all vertices, the list scans total the sum of the degrees, which is E for a directed graph and 2E for an undirected one. The matrix scans V entries per vertex, which gives V^2.
Details that affect correctness
- Undirected graphs: The matrix is symmetric, so
mat[u][v] == mat[v][u]. The list stores each edge twice, once in each endpoint's list. The sum of the list lengths is 2E, and the sum of all matrix entries (unweighted, no loops) is also 2E. - Directed graphs: The list stores each edge once, so the sum of the list lengths is E. The row sum of the matrix at u is the out-degree. The column sum is the in-degree.
- Parallel edges: The matrix has one cell per vertex pair, so a second edge overwrites the first (or you must keep the smaller weight). The list keeps both. Use a list if the problem allows multi-edges.
- Self-loops: A loop u→u is
mat[u][u]in the matrix. In an undirected list, it appears once or twice depending on your convention. Decide the convention before you count degrees. - Matrix powers: For an unweighted matrix A, entry
(A^k)[u][v]counts walks of length k from u to v. This is a common GATE trick, and only the matrix supports it directly.
Choosing in practice
A graph is sparse when E is about V (a road network, a tree) and dense when E is about V^2 (a complete graph). Use a list for sparse graphs. A matrix with V = 100,000 needs 10^10 cells, while a sparse list needs only a few hundred thousand entries.
Use a matrix when the graph is dense, when you query "is there an edge between u and v?" very often, or when the algorithm is naturally cubic over all pairs, as in Floyd-Warshall. Floyd-Warshall already costs O(V^3), so the matrix's O(V^2) space adds nothing.
Algorithm bounds depend on this choice. BFS and DFS are O(V + E) with lists and O(V^2) with a matrix. Dijkstra with a binary heap is O((V + E) log V) with lists. Prim's algorithm with a plain array and a matrix is O(V^2), which beats the heap version when E is near V^2.
Exercise
A connected undirected graph has V = 1000 and E = 3000. Roughly how many neighbour-entry visits does a full BFS make with an adjacency list, and how many cell reads does it make with an adjacency matrix?
Show answer
With a list, BFS reads each of the 2E = 6000 list entries once, and it dequeues V = 1000 vertices, so the work is about V + 2E = 7000 steps, which is O(V + E). With a matrix, it scans one row of 1000 cells for each of the 1000 vertices, which is 1,000,000 cell reads, or O(V^2).
Exercise
A directed graph is stored as an adjacency list. The total number of entries across all lists is 40. Then the same edges are treated as undirected and stored again. What is the new total, assuming no self-loops and no pair of opposite edges u→v and v→u?
Show answer
The directed graph has E = 40 edges, because each directed edge appears once. Treated as undirected, each edge appears in both endpoints' lists, so the total is 2E = 80.