Sub topic 3
Labeling Components with Breadth-First Search
This chapter assumes you can read Python functions and loops, know how a queue works (first in, first out), and have met the adjacency list from the earlier chapter. You should also know the definition of a connected component: a maximal set of vertices in which every pair is joined by some path.
The goal is concrete. Given an undirected graph with n vertices numbered 0 to n - 1, produce two things:
count, the number of connected components.label, a list wherelabel[v]is the index of the component containing vertexv.
With a label list you can answer "are u and v connected?" in constant time by comparing label[u] == label[v]. You can also group vertices, measure component sizes, or pick the largest component.
The Working Model
Breadth-first search (BFS) visits every vertex reachable from a starting vertex. It goes outward in layers: first the start, then its neighbors, then their neighbors, and so on. Everything BFS reaches from one start vertex belongs to the same component, because it reached each of those vertices by a path. It also reaches every vertex in that component, because any vertex with a path to the start will eventually be found by following that path edge by edge.
So one BFS discovers exactly one component. To find all of them, wrap BFS in an outer loop over every vertex:
- Walk through vertices
0, 1, ..., n - 1. - If a vertex already has a label, skip it. An earlier BFS already found its component.
- Otherwise, the vertex starts a new component. Give it the next label and run BFS from it, putting that same label on everything the BFS reaches.
The Implementation
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])A few design choices matter here:
- The label list does two jobs. The value
-1means "not yet visited", and any other value is the component index. You don't need a separatevisitedset. - Labels are assigned when a vertex is enqueued, not when it is dequeued. This guarantees each vertex enters the queue at most once. The common-errors section below shows why this matters.
deque.popleft()runs in O(1). A plain Python list withpop(0)shifts every remaining element, which costs O(k) per pop.- The outer loop runs over
range(n), not over the edges. Vertex 5 appears in no edge, but the loop still reaches it and gives it its own component.
Tracing the Example
The edge list [(0, 1), (1, 2), (3, 4)] with n = 6 produces this adjacency list: 0: [1], 1: [0, 2], 2: [1], 3: [4], 4: [3], 5: [].
| Step | Action | Queue after | label after | count |
|---|---|---|---|---|
| 1 | start = 0, unlabeled, label it 0 | [0] | [0, -1, -1, -1, -1, -1] | 0 |
| 2 | pop 0, neighbor 1 unlabeled | [1] | [0, 0, -1, -1, -1, -1] | 0 |
| 3 | pop 1, neighbor 0 labeled, neighbor 2 unlabeled | [2] | [0, 0, 0, -1, -1, -1] | 0 |
| 4 | pop 2, neighbor 1 labeled | [] | unchanged | 1 |
| 5 | start = 1, 2 already labeled, skip | none | unchanged | 1 |
| 6 | start = 3, label it 1 | [3] | [0, 0, 0, 1, -1, -1] | 1 |
| 7 | pop 3, neighbor 4 unlabeled | [4] | [0, 0, 0, 1, 1, -1] | 1 |
| 8 | pop 4, neighbor 3 labeled | [] | unchanged | 2 |
| 9 | start = 4 skip; start = 5, label it 2 | [5] | [0, 0, 0, 1, 1, 2] | 2 |
| 10 | pop 5, no neighbors | [] | unchanged | 3 |
Component indices come out in the order of each component's smallest vertex. The loop scans vertices in increasing order, so the first vertex it meets in any component is that component's smallest member.
Vertices That Are Not 0 to n − 1
Real data often uses strings or IDs as vertex names. You can either map them to integers first, or switch the list-based structures to dictionaries:
from collections import deque
def label_components(vertices, edges):
adj = {v: [] for v in vertices}
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
label = {}
count = 0
for start in adj:
if start in label:
continue
label[start] = count
queue = deque([start])
while queue:
u = queue.popleft()
for v in adj[u]:
if v not in label:
label[v] = count
queue.append(v)
count += 1
return count, label
print(label_components(["a", "b", "c", "d"], [("a", "b"), ("c", "d")]))
# (2, {'a': 0, 'b': 0, 'c': 1, 'd': 1})Here "absent from label" plays the role that -1 played before. If an edge names a vertex that is missing from vertices, adj[u] raises KeyError. That is usually what you want, because it exposes bad input. If you would rather add such vertices silently, use collections.defaultdict(list) for adj and add every edge endpoint as a key.
Common Errors
Marking on dequeue instead of enqueue
A tempting version checks and marks a vertex only when it leaves the queue. That version still works if it skips already-seen vertices on pop. But one vertex can then sit in the queue many times, once for each labeled neighbor that saw it before it was processed. The function below counts how many pushes each strategy makes on a complete graph with 5 vertices:
from collections import deque
def enqueues(adj, start, mark_on_enqueue):
seen = set()
queue = deque([start])
if mark_on_enqueue:
seen.add(start)
pushes = 1
while queue:
u = queue.popleft()
if not mark_on_enqueue:
if u in seen:
continue
seen.add(u)
for v in adj[u]:
if v not in seen:
if mark_on_enqueue:
seen.add(v)
queue.append(v)
pushes += 1
return pushes
n = 5
complete = [[v for v in range(n) if v != u] for u in range(n)]
print(enqueues(complete, 0, True)) # 5
print(enqueues(complete, 0, False)) # 11Marking on enqueue gives exactly n pushes. Marking on dequeue can push up to one entry per edge endpoint, so queue memory grows to O(E) instead of O(V). If you also forget the skip-on-pop check, vertices get processed repeatedly, and the extra work multiplies.
Adding only one direction of each edge
If you write adj[u].append(v) without adj[v].append(u), BFS from v cannot get back to u. With edges [(1, 0)], a BFS from 0 finds nothing, so 0 gets label 0. Then the BFS from 1 reaches 0, which is already labeled, and 1 gets label 1. You get two components where there should be one. An undirected edge must appear in both lists.
Looping over edges instead of vertices
Driving the outer loop from the edge list drops isolated vertices, which have no edges. Always loop over the full vertex set.
Using a list as the queue
queue.pop(0) on a list is O(k). On a path-shaped component with a million vertices the queue stays small, so the cost hides. On a star-shaped component the queue holds nearly every vertex at once, and the total cost becomes quadratic. Use deque.
Edge Cases
| Input | Result | Why |
|---|---|---|
| `n = 0`, no edges | `(0, [])` | The outer loop never runs |
| `n = 4`, no edges | `(4, [0, 1, 2, 3])` | Each vertex is its own component |
| One component covering all vertices | `(1, [0, 0, ...])` | The first BFS labels everything; later starts are all skipped |
| Edge endpoint `>= n` | `IndexError` | The adjacency list has no slot for it; check input first |
What BFS Gives You Beyond Labels
BFS visits vertices in order of their distance, in edges, from the start. If you record dist[v] = dist[u] + 1 at the moment you label v, you get shortest-path distances inside each component at no extra asymptotic cost. Recording parent[v] = u at the same moment gives a BFS tree you can use to rebuild those shortest paths. This is the main practical reason to choose BFS over DFS for labeling. If you only need labels, either traversal works, and the next chapter covers the DFS version.
The cost of the whole procedure is linear in the size of the graph. Each vertex is enqueued once and each adjacency entry is examined once. A later chapter works through why this totals O(V + E).
Exercise
Modify connected_components so it also returns a list sizes, where sizes[i] is the number of vertices in component i, without making a second pass over label. What is the output for n = 6, edges [(0, 1), (1, 2), (3, 4)]?
Show answer
Set sizes = [] before the outer loop. When a new component starts, append 1 with sizes.append(1), and do sizes[count] += 1 each time a neighbor is labeled. Return count, label, sizes. The output is (3, [0, 0, 0, 1, 1, 2], [3, 2, 1]).
Exercise
A colleague's BFS labeling gives count = 2 for n = 2, edges [(1, 0)]. Name the most likely bug and explain what happened.
Show answer
The adjacency list was built in only one direction, adj[1] = [0] with adj[0] = []. BFS from 0 finds no neighbors, so 0 gets label 0 and count becomes 1. BFS from 1 sees that 0 is already labeled, so 1 gets label 1 and count becomes 2. Adding adj[v].append(u) fixes it.
Exercise
In a star graph where vertex 0 connects to vertices 1 through k, what is the largest the queue gets when you mark on enqueue? Why would a list with pop(0) be slow on this graph but fine on a long path?
Show answer
After 0 is popped, all k leaves are enqueued at once, so the queue peaks at k entries. Each pop(0) then shifts up to k elements, which is O(k²) in total. On a path the queue never holds more than one or two entries, so each pop(0) is cheap.
Exercise
Extend the BFS so it records dist[v], the number of edges from the start vertex of v's component to v. What is dist for n = 5, edges [(0, 1), (0, 2), (2, 3)], where vertex 4 is isolated?
Show answer
Initialize dist = [-1] * n. Set dist[start] = 0 when a component starts and dist[v] = dist[u] + 1 when labeling neighbor v. The result is [0, 1, 1, 2, 0]. Vertex 3 is two edges from 0 through 2, and vertex 4 starts its own component at distance 0.