Sub topic 4
Labeling Components with Iterative Depth-First Search
This chapter assumes you can build an adjacency list from an edge list, that you know what a connected component is, and that you have seen the breadth-first search (BFS) labeling loop from the previous chapter. You should also be comfortable with Python lists used as stacks.
Depth-first search (DFS) finds the same components as BFS. The difference is the order in which it visits vertices. BFS takes vertices from a queue, so it works outward layer by layer. DFS takes them from a stack, so it follows one path as deep as it can before backing up. For labeling components, the order does not matter. Every vertex reachable from the start ends up in the same component either way.
Why Iterative and Not Recursive
The textbook form of DFS is recursive: visit a vertex, then call yourself on each unvisited neighbor. In Python this fails on large inputs. CPython's default recursion limit is about 1000 frames. A path graph with 10,000 vertices makes the recursive version raise RecursionError partway through. An explicit stack is an ordinary list on the heap, so its depth is limited only by memory.
The Algorithm
The outer loop tries every vertex as a possible starting point. Each unseen vertex starts a new component. The inner loop pops a vertex, records it, and pushes its unseen neighbors.
def components_dfs(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
seen = [False] * n
result = []
for start in range(n):
if seen[start]:
continue
seen[start] = True
stack = [start]
component = []
while stack:
u = stack.pop()
component.append(u)
for v in adj[u]:
if not seen[v]:
seen[v] = True
stack.append(v)
result.append(sorted(component))
return result
print(components_dfs(6, [(0, 1), (1, 2), (3, 4)]))
# [[0, 1, 2], [3, 4], [5]]This version returns each component as a sorted list of vertices instead of a label array. You can get labels from it with one pass: for index i and component c, set label[v] = i for each v in c. You can also write count into a label list inside the loop, the same way the BFS version does.
Tracing a Small Example
The graph above has adj[0] = [1], adj[1] = [0, 2], adj[2] = [1], adj[3] = [4], adj[4] = [3], and adj[5] = [].
| Step | Popped | Pushed | Stack after | Component |
|---|---|---|---|---|
| start 0 | – | 0 | [0] | [] |
| 1 | 0 | 1 | [1] | [0] |
| 2 | 1 | 2 | [2] | [0, 1] |
| 3 | 2 | – | [] | [0, 1, 2] |
The outer loop then skips 1 and 2, starts a new component at 3, and finally finds 5 alone.
Common Errors
| Mistake | Effect | Fix |
|---|---|---|
| Marking `seen` when popping instead of when pushing, without a check on pop | A vertex gets processed more than once and shows up twice in its component | Mark when pushing, as shown above |
| Adding each edge in only one direction | A vertex is missed when it is reachable only through an edge stored on the other side | Append both `adj[u]` and `adj[v]` |
| Forgetting the outer loop | Only the first component is found | Loop over every vertex as a possible start |
| Skipping isolated vertices | Components of size one disappear | Build `adj` for all `n` vertices, not only those in `edges` |
Because each vertex is marked before it is pushed, it enters the stack at most once. The stack never holds more than V entries, and each adjacency list is scanned once. The next chapter turns this observation into the O(V + E) bound.
Exercise
Suppose you move seen[v] = True so that it runs after u = stack.pop() (marking u instead), and add if seen[u]: continue right after the pop. Is the output still correct, and how does the maximum stack size change?
Show answer
The components are still correct, because the check on pop discards duplicates before they are recorded. But a vertex can now be pushed once for each already-processed neighbor that saw it as unmarked, so the stack can grow to O(E) entries instead of at most V.
Exercise
Change components_dfs so that it returns (count, label) in the same format as the BFS function, where label[v] is the component index of vertex v.
Show answer
Create label = [-1] * n and use label[v] == -1 in place of seen. Before the inner loop, set label[start] = count. When you push a neighbor, set label[v] = count. After the inner loop finishes, add 1 to count. Return count, label. For the sample input this gives (3, [0, 0, 0, 1, 1, 2]).