Sub topic 1
Representing a Graph as an Adjacency List
To find connected components, you first need the graph stored in a form your code can walk through quickly. Problems usually give you an edge list, which is a list of pairs (u, v). That format is easy to write down, but it is slow to answer "who are the neighbors of u?" An adjacency list answers that question directly. Every algorithm later in this tutorial starts from one.
Prerequisites
This chapter assumes you know:
- Basic Python: lists, loops, functions, and classes
- What vertices and edges are, and the difference between directed and undirected edges
- Big-O notation for time and space
From edge list to adjacency list
An adjacency list stores, for each vertex, the list of vertices it shares an edge with. If the vertices are numbered 0 to n - 1, a list of lists works well: adj[u] holds the neighbors of u.
Here is a running example with 6 vertices and the edges (0, 1), (1, 2), and (3, 4). Vertex 5 has no edges.
def build_adjacency(n, edges, directed=False):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
if not directed:
adj[v].append(u)
return adj
adj = build_adjacency(6, [(0, 1), (1, 2), (3, 4)])
for u, neighbors in enumerate(adj):
print(u, neighbors)
# 0 [1]
# 1 [0, 2]
# 2 [1]
# 3 [4]
# 4 [3]
# 5 []In an undirected graph, each edge (u, v) goes into both adj[u] and adj[v]. A directed edge goes only into adj[u].
Cost
| Operation | Edge list | Adjacency list |
|---|---|---|
| Space | O(E) | O(V + E) |
| List neighbors of `u` | O(E) | O(deg(u)) |
| Build from edge list | none | O(V + E) |
Visiting every vertex's neighbors once costs O(V + E) in total. That sum is where the O(V + E) running time of later traversals comes from.
Vertices that are not 0 to n − 1
When vertices are strings or sparse IDs, use a dictionary. You have to add isolated vertices yourself, because no edge will create them.
from collections import defaultdict
def build_adjacency_dict(vertices, edges):
adj = defaultdict(list)
for v in vertices:
adj[v] # touching the key creates an empty list for isolated vertices
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return dict(adj)
print(build_adjacency_dict(["a", "b", "c", "z"], [("a", "b"), ("b", "c")]))
# {'a': ['b'], 'b': ['a', 'c'], 'c': ['b'], 'z': []}Common errors
bad = [[]] * 3
bad[0].append(1)
print(bad) # [[1], [1], [1]]
good = [[] for _ in range(3)]
good[0].append(1)
print(good) # [[1], [], []]Other mistakes to watch for:
- Adding only one direction for an undirected edge. A traversal from
vwill then never reachu, and you get too many components. - Losing isolated vertices. If you build the dictionary only from edges, vertex
5never appears and the component count comes out one too low. - Off-by-one vertex numbering. Inputs numbered from 1 to n need either
n + 1slots or subtracting 1 from each endpoint. - Duplicate edges and self-loops. These are harmless for finding components as long as your traversal tracks which vertices it has visited. They do inflate the neighbor lists.
Exercise
Given n = 4 and the 1-indexed edges [(1, 2), (2, 3)], write the 0-indexed adjacency list for the undirected graph. How many vertices have an empty neighbor list?
Show answer
Subtract 1 from each endpoint to get edges (0, 1) and (1, 2). The list is [[1], [0, 2], [1], []]. One vertex, vertex 3, has an empty list. It is an isolated vertex and will form its own component.
Exercise
Why does [[]] * n produce wrong results while [[] for _ in range(n)] does not?
Show answer
The multiplication copies the reference to a single list object n times, so every slot points to the same list. The comprehension evaluates [] once per iteration and creates n separate lists.