Sub topic 4
Labeling Components with Iterative Depth-First Search
This chapter assumes you can read Python functions and lists, know how a stack works, and have seen the adjacency-list construction and the BFS labeling loop from the earlier chapters. Here we find the same components with depth-first search (DFS). We write DFS with an explicit stack instead of recursion, and we look at the mistakes people most often make when they convert one into the other.
The Working Model
DFS and BFS share one outer loop. You scan the vertices in order. Each time you reach a vertex that is not yet marked, you have found a new component, and you explore everything reachable from it. The two differ only in the container that holds the vertices waiting to be explored:
| Search | Container | Removal | Effect on exploration order |
|---|---|---|---|
| BFS | Queue (`deque`) | `popleft()`, oldest first | Spreads out level by level |
| DFS | Stack (`list`) | `pop()`, newest first | Goes deep along one path before backtracking |
For labeling, the order of exploration does not matter. Each component is the set of vertices reachable from its start vertex, and both searches reach exactly that set. So you can choose DFS for other reasons. A stack is a plain Python list, and the vertex lists DFS collects are handy for later steps such as sorting, filtering, or reporting.
The Implementation
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]]The function returns a list of components, and each component is a sorted list of vertex IDs. The BFS version returned a label array instead. Each form converts easily into the other:
def components_to_labels(n, components):
label = [-1] * n
for index, comp in enumerate(components):
for v in comp:
label[v] = index
return label
print(components_to_labels(6, [[0, 1, 2], [3, 4], [5]]))
# [0, 0, 0, 1, 1, 2]Pick the form your next step needs. A label array answers "are a and b in the same component?" in O(1). A component list answers "what is in this component?" without scanning all vertices.
Tracing the Example
The adjacency list for the example is 0:[1], 1:[0,2], 2:[1], 3:[4], 4:[3], 5:[].
| Step | Popped `u` | Neighbors pushed | Stack after | Component so far |
|---|---|---|---|---|
| start 0 | – | – | `[0]` | `[]` |
| 1 | 0 | 1 | `[1]` | `[0]` |
| 2 | 1 | 2 (0 already seen) | `[2]` | `[0, 1]` |
| 3 | 2 | none | `[]` | `[0, 1, 2]` |
| start 3 | – | – | `[3]` | `[]` |
| 4 | 3 | 4 | `[4]` | `[3]` |
| 5 | 4 | none | `[]` | `[3, 4]` |
| start 5 | 5 | none | `[]` | `[5]` |
The outer loop skips vertices 1, 2, and 4 because they are already marked when it reaches them. That skip is what stops one component from being counted twice.
Why Not Recursion?
The textbook DFS is recursive, and it is shorter:
def components_recursive(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
seen = [False] * n
def visit(u, comp):
seen[u] = True
comp.append(u)
for v in adj[u]:
if not seen[v]:
visit(v, comp)
result = []
for s in range(n):
if not seen[s]:
comp = []
visit(s, comp)
result.append(sorted(comp))
return result
n = 5000
path = [(i, i + 1) for i in range(n - 1)]
try:
components_recursive(n, path)
except RecursionError as e:
print(type(e).__name__) # RecursionError
print(len(components_dfs(n, path))) # 1CPython limits the call stack to about 1000 frames by default. On a path graph, every vertex adds one nested call, so a component with 5000 vertices on a path crashes the recursive version. The iterative version keeps its stack in a heap-allocated list, so its only limit is memory.
Mark on Push or Mark on Pop
The most common bug in iterative DFS is marking a vertex at the wrong moment. The code above marks a vertex when it is pushed. Some people mark it when it is popped instead, which seems natural because that is when the vertex is "visited":
def components_buggy(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
stack = [start]
component = []
while stack:
u = stack.pop()
seen[u] = True
component.append(u)
for v in adj[u]:
if not seen[v]:
stack.append(v)
result.append(sorted(component))
return result
print(components_buggy(3, [(0, 1), (1, 2), (0, 2)]))
# [[0, 1, 1, 2]]On a triangle, vertex 1 is pushed twice: once as a neighbor of 0 and again as a neighbor of 2, both times before it is popped and marked. It is then appended to the component twice. The component count is still right, but sizes and listings are wrong. In a dense graph the stack can also grow to O(E) entries instead of O(V).
Mark-on-pop does work if you add a guard that skips stale entries:
def components_mark_on_pop(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
stack = [start]
component = []
while stack:
u = stack.pop()
if seen[u]:
continue
seen[u] = True
component.append(u)
for v in adj[u]:
if not seen[v]:
stack.append(v)
result.append(sorted(component))
return result
print(components_mark_on_pop(3, [(0, 1), (1, 2), (0, 2)]))
# [[0, 1, 2]]| Strategy | Duplicates on stack | Peak stack size | Visit order |
|---|---|---|---|
| Mark on push | None | At most V | Not true DFS preorder |
| Mark on pop without guard | Yes, and the output is wrong | Up to O(E) | – |
| Mark on pop with guard | Yes, but skipped | Up to O(E) | Matches recursive preorder if neighbors are pushed in reverse |
For labeling, mark-on-push is the better default. It uses the least memory, and the visit order does not affect the answer.
A Note on Visit Order
The mark-on-push version is not a faithful copy of recursive DFS. It finishes scanning all of u's neighbors before going deeper, and it explores them last-pushed-first. The set of vertices it reaches is correct. The order, and the DFS tree it implies, differ from the recursive version.
This matters once an algorithm depends on order. Kosaraju's algorithm for strongly connected components needs each vertex's finish time, which is the moment all of its descendants have been explored. Recording that time requires a stack of (vertex, next-neighbor-index) pairs that imitates the recursion exactly. A later chapter builds that version. For undirected labeling, the simple stack is enough.
Common Errors
- Forgetting the reverse edge. If you append only
adj[u].append(v)for an undirected graph, vertices reachable only "backwards" are missed, and one component splits into several. - Resetting
seenper start vertex. Theseenarray must persist across the whole outer loop. If you reset it, every vertex starts a new component. - Skipping isolated vertices. If you build the vertex set from the edge list instead of
range(n), vertex 5 in the example disappears. Isolated vertices are components of size one. - Using
list.pop(0). That gives BFS order with O(V) cost per pop. If you want a queue, usedeque. If you want DFS, usepop().
Exercise
Run components_buggy on the 4-cycle with edges (0,1), (1,2), (2,3), (3,0). Which vertex appears twice in the output, and why?
Show answer
The output is [[0, 1, 2, 3, 3]]. Popping 0 pushes 1 and 3. Popping 3 pushes 2. Popping 2 finds 1 and 3. Vertex 3 is already marked, but 1 is not, so 1 is pushed a second time. Popping 1 pushes nothing new, then the stale 1 is popped and appended again... Tracing carefully: adj is 0:[1,3], 1:[0,2], 2:[1,3], 3:[2,0]. The stack goes [1,3], pop 3 (mark), push 2 → [1,2], pop 2 (mark), push 1 → [1,1], pop 1 (mark), pop 1 again. Vertex 1 is appended twice, so the output is [[0, 1, 1, 2, 3]]. It was pushed twice before it was first popped and marked.
Exercise
Modify components_dfs so that it returns the size of the largest component instead of the list of components. What does it return for n = 7 and edges (0,1), (1,2), (3,4), (4,5), (5,3)?
Show answer
Track the length of each component and keep the maximum: replace result.append(sorted(component)) with best = max(best, len(component)), initialize best = 0 before the outer loop, and return best. The components are {0,1,2}, {3,4,5}, and {6}, so it returns 3.
Exercise
A recursive DFS works on your test graphs but fails in production with RecursionError. The production graph has 200,000 vertices and every component has at most 50 vertices. Is component size or graph size the likely cause, and does that make the failure surprising?
Show answer
Recursion depth is bounded by the longest DFS path inside a single component, not by the total number of vertices, so components of at most 50 vertices cannot reach the limit of about 1000. The failure is surprising and points to a data problem: the production graph probably contains at least one large component, for example from a bad edge that joins many groups. Switching to an explicit stack fixes the crash, but you should also check the component sizes.