Sub topic 3
Labeling Components with Breadth-First Search
This chapter assumes you can read Python lists, loops, and functions. It also assumes you know what a queue is and how an adjacency list stores a graph, since the earlier chapters covered both. The goal here is a working labeler. Given an undirected graph, it returns the number of connected components and the component index of every vertex.
The idea
Breadth-first search (BFS) starts at one vertex and visits every vertex reachable from it, layer by layer, using a queue. One BFS run reaches exactly one connected component, because it can only follow edges, and edges never cross between components.
To label the whole graph, you need an outer loop:
- Walk through the vertices in order.
- If a vertex has no label yet, it starts a new component. Give it the next component number and run BFS from it.
- During that BFS, give every vertex you reach the same number.
- When BFS ends, the component is finished. Move on to the next unlabeled vertex.
The label array does two jobs. It records the answer, and it also marks vertices as visited. A value of -1 means "not reached yet."
The code
from collections import deque
def connected_components(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
label = [-1] * n
count = 0
for start in range(n):
if label[start] != -1:
continue
label[start] = count
queue = deque([start])
while queue:
u = queue.popleft()
for v in adj[u]:
if label[v] == -1:
label[v] = count
queue.append(v)
count += 1
return count, label
print(connected_components(6, [(0, 1), (1, 2), (3, 4)]))
# (3, [0, 0, 0, 1, 1, 2])Tracing the example
The graph has six vertices and the edges 0–1, 1–2, and 3–4.
| Step | Start vertex | Vertices labeled | count afterward |
|---|---|---|---|
| 1 | 0 | 0, 1, 2 get label 0 | 1 |
| 2 | 1, 2 | skipped (already labeled) | 1 |
| 3 | 3 | 3, 4 get label 1 | 2 |
| 4 | 4 | skipped | 2 |
| 5 | 5 | 5 gets label 2 (no neighbors) | 3 |
Vertex 5 has no edges, so it is a component on its own. The outer loop still finds it, because the loop goes over every vertex, including ones that never show up in the edge list.
Common errors
- Adding only one direction of each edge. In an undirected graph,
adj[u].append(v)needs a matchingadj[v].append(u). If you leave it out, BFS from some vertices misses part of their component, and you count too many components. - Marking vertices when you dequeue them instead of when you enqueue them. If you set the label only after
popleft(), the same vertex can be added to the queue several times by different neighbors. The answer is still correct, but the queue grows and the work is repeated. Labeling at enqueue time means each vertex enters the queue at most once. - Looping over the edges instead of the vertices. Isolated vertices like 5 have no edges, so a loop driven by the edge list never sees them.
- Using
list.pop(0)as a queue. Each call shifts the whole list, which takes O(n) time.deque.popleft()takes O(1). - Resetting
countinside the loop or incrementing it for skipped vertices. Increase it only after a BFS finishes.
The order in which BFS visits vertices makes no difference to the result. Any traversal that reaches every vertex reachable from the start gives the same labels. The next chapter uses this fact to replace the queue with a stack.
Exercise
What does connected_components(5, [(0, 4), (1, 2)]) return?
Show answer
(3, [0, 1, 1, 2, 0]). Vertex 0 starts component 0 and BFS reaches 4. Vertex 1 starts component 1 and reaches 2. Vertex 3 has no edges, so it becomes component 2.
Exercise
Suppose you move the line label[v] = count so that it runs right after u = queue.popleft() (as label[u] = count), and you change the check to only skip u if it was already labeled. Are the final labels still correct, and what is the cost?
Show answer
The labels are still correct, because every reachable vertex is labeled before BFS finishes. The cost is that a vertex can be enqueued once for each neighbor that sees it before it is dequeued. The queue can then hold up to O(E) entries instead of O(V), and some work is repeated.