Sub topic 3
Depth-First Search Refresher
This chapter assumes you can read Python functions and loops, know what an adjacency list is, and have seen depth-first search (DFS) at a conceptual level. The goal here is to pin down the parts of DFS that cycle detection relies on: the visited set, the outer loop over all vertices, and the idea of a vertex being "on the current path."
The Working Model
DFS starts at a vertex and follows one edge as far as it can before backing up. Each vertex passes through three moments:
- Discovery: DFS reaches the vertex for the first time and marks it visited.
- Exploration: DFS visits each neighbor that has not been visited yet.
- Finish: every neighbor has been handled, so DFS backs up to the vertex that discovered this one.
Between discovery and finish, a vertex sits on the recursion stack, the chain of calls from the start vertex down to the current one. That chain is the current DFS path. Later chapters use this fact directly: an edge that points back to a vertex still on the path closes a loop.
A Complete Implementation
The version below records both discovery order and finish order. It runs DFS from every unvisited vertex, so it covers graphs with more than one component.
def dfs_all(adj):
n = len(adj)
visited = [False] * n
order = []
finish = []
def dfs(u):
visited[u] = True
order.append(u)
for v in adj[u]:
if not visited[v]:
dfs(v)
finish.append(u)
for s in range(n):
if not visited[s]:
dfs(s)
return order, finish
adj = [[1, 2], [3], [3], [], [5], []]
print(dfs_all(adj))Running it prints:
([0, 1, 3, 2, 4, 5], [3, 1, 2, 0, 5, 4])Tracing the Example
| Step | Event | Current path |
|---|---|---|
| 1 | discover 0 | 0 |
| 2 | discover 1 | 0, 1 |
| 3 | discover 3 | 0, 1, 3 |
| 4 | finish 3, finish 1 | 0 |
| 5 | discover 2; 3 already visited | 0, 2 |
| 6 | finish 2, finish 0 | (empty) |
| 7 | outer loop: discover 4, then 5 | 4, 5 |
| 8 | finish 5, finish 4 | (empty) |
At step 5, vertex 2 has an edge to 3, but 3 is already visited and finished. That edge does not form a cycle. The graph has no cycle, even though DFS met a visited vertex. A vertex being visited is a different condition from a vertex being on the current path. The rest of the tutorial depends on that difference.
Common Errors
- Skipping the outer loop. If you call
dfs(0)only, vertices 4 and 5 are never seen. Cycle detection that starts from one vertex misses cycles in other components. - Marking visited too late in an iterative version. If you push neighbors onto a stack and mark them visited only when you pop them, a vertex can be pushed many times. That breaks the O(V + E) bound and confuses path tracking.
- Treating "visited" as "on the path." As step 5 shows, these differ in directed graphs. A single boolean array cannot tell them apart.
- Hitting recursion limits. Python's default recursion limit is about 1000 calls, so a long chain of vertices raises
RecursionError. A later chapter replaces recursion with an explicit stack.
Exercise
In the example graph, which vertices are on the current DFS path at the moment vertex 3 is discovered, and which vertices have already finished?
Show answer
The path is 0, 1, 3. No vertex has finished yet. Vertex 3 is the first to finish, right after it is discovered, because it has no outgoing edges.
Exercise
If you remove the outer loop and call only dfs(0), what are the discovery and finish orders?
Show answer
Discovery order is [0, 1, 3, 2] and finish order is [3, 1, 2, 0]. Vertices 4 and 5 are never visited because no edge leads to them from vertex 0.