Sub topic 3
Depth-First Search Refresher
Every cycle detection method in the DFS-based chapters of this tutorial is a small modification of plain depth-first search. Before adding cycle logic, it helps to have a precise picture of what DFS does, what state it keeps, and where implementations commonly go wrong.
This chapter assumes you can read Python functions and loops, know what an adjacency list is, and have seen DFS at a conceptual level. It does not cover edge classification or cycle detection. Those come in later chapters, and both depend on the details reviewed here.
The Working Model
Depth-first search explores a graph by always following an unexplored edge from the most recently discovered vertex that still has one. When a vertex has no unexplored edges left, the search backtracks to the vertex it came from and continues there.
DFS keeps three pieces of state:
- Visited marks. A visited mark is a flag that records that a vertex has been discovered, so the search never enters it twice. Without it, DFS loops forever on any graph with a cycle.
- The current path. This is the chain of vertices from the starting vertex to the one being explored. In recursive DFS, the call stack holds it. In iterative DFS, an explicit stack holds it.
- Parent pointers (optional). A parent pointer records which vertex discovered each vertex. Together, the parent pointers form the DFS tree, or a DFS forest when the graph has several components.
The current path matters most for this tutorial. In a directed graph, a cycle exists exactly when DFS finds an edge leading back to a vertex that is still on the current path. Visited marks by themselves cannot tell you that, because they do not separate "on the path right now" from "finished earlier".
Recursive DFS with Discovery and Finish Times
The version below records a discovery time for each vertex, which is the moment it is first entered, and a finish time, which is the moment all of its descendants are done. A single counter, clock, provides both.
def dfs_times(adj):
n = len(adj)
visited = [False] * n
parent = [-1] * n
discover = [0] * n
finish = [0] * n
clock = 0
def visit(u):
nonlocal clock
visited[u] = True
clock += 1
discover[u] = clock
for v in adj[u]:
if not visited[v]:
parent[v] = u
visit(v)
clock += 1
finish[u] = clock
for s in range(n):
if not visited[s]:
visit(s)
return discover, finish, parent
adj = [
[1, 2], # 0
[3], # 1
[3], # 2
[], # 3
[5], # 4
[], # 5
]
d, f, p = dfs_times(adj)
print(d) # [1, 2, 6, 3, 9, 10]
print(f) # [8, 5, 7, 4, 12, 11]
print(p) # [-1, 0, 0, 1, -1, 4]The graph is directed. Vertices 0 through 3 form one region and vertices 4 and 5 form another, with no edges between the two.
Tracing the Run
| Step | Event | clock | Current path |
|---|---|---|---|
| 1 | discover 0 | 1 | 0 |
| 2 | discover 1 (parent 0) | 2 | 0, 1 |
| 3 | discover 3 (parent 1) | 3 | 0, 1, 3 |
| 4 | finish 3 | 4 | 0, 1 |
| 5 | finish 1 | 5 | 0 |
| 6 | discover 2 (parent 0) | 6 | 0, 2 |
| 7 | edge 2 → 3: 3 already visited, skip | 6 | 0, 2 |
| 8 | finish 2 | 7 | 0 |
| 9 | finish 0 | 8 | (empty) |
| 10 | discover 4 (outer loop) | 9 | 4 |
| 11 | discover 5 (parent 4) | 10 | 4, 5 |
| 12 | finish 5 | 11 | 4 |
| 13 | finish 4 | 12 | (empty) |
Step 7 previews a later chapter. When DFS looks at edge 2 → 3, vertex 3 is visited but no longer on the current path, because it finished at time 4. Following that edge cannot lead back to 2, so it is not a cycle. If vertex 3 had still been on the path, the edge would close a cycle. The visited flag is identical in both situations, which is why directed cycle detection needs more state than plain DFS keeps.
The Parenthesis Property
Look at each vertex's interval from discovery to finish: 0 is [1, 8], 1 is [2, 5], 3 is [3, 4], and 2 is [6, 7]. For any two vertices, their intervals are either nested or disjoint. They never partly overlap. This is the parenthesis property. If you write "(u" at discovery and "u)" at finish, the result is a balanced sequence of parentheses:
(0 (1 (3 3) 1) (2 2) 0) (4 (5 5) 4)
Two consequences matter later:
- Vertex v is a descendant of u in the DFS tree exactly when v's interval sits inside u's interval.
- At any moment, the vertices that have been discovered but not finished are exactly the vertices on the current path.
The second point is the basis of three-color DFS. "Discovered but not finished" will be called gray, "finished" will be called black, and an edge into a gray vertex will mean a cycle.
Covering Every Component
The for s in range(n) loop at the bottom of dfs_times is easy to forget. A single call to visit(0) reaches only the vertices reachable from 0, so vertices 4 and 5 would never be explored. A cycle detector built on such a traversal would return "no cycle" for any graph whose only cycle lies outside the starting vertex's reach.
In directed graphs, reachability is one-way. In the example, if an edge 5 → 0 existed, starting at 0 would still never reach 5. The outer loop is required even when the graph looks connected on paper.
Iterative DFS with an Explicit Stack
Python limits recursion depth. sys.getrecursionlimit() returns 1000 by default, so recursive DFS on a path with a few thousand vertices raises RecursionError. An explicit stack avoids this.
def dfs_order_iterative(adj, start):
visited = [False] * len(adj)
order = []
stack = [start]
while stack:
u = stack.pop()
if visited[u]:
continue
visited[u] = True
order.append(u)
for v in reversed(adj[u]):
if not visited[v]:
stack.append(v)
return order
adj = [[1, 2], [3], [3], [], [5], []]
print(dfs_order_iterative(adj, 0)) # [0, 1, 3, 2]Pushing neighbors in reverse means the first neighbor is popped first, so the discovery order matches the recursive version. The if visited[u]: continue check is needed because a vertex can be pushed more than once before it is popped.
This version has a limitation that matters for cycle detection. A vertex leaves the stack as soon as it is popped, before its descendants are explored, so the stack does not hold the current path and the code cannot record finish times. A later chapter fixes this by storing a neighbor iterator with each stack entry and popping a vertex only when that iterator runs out.
Mark-on-Pop Versus Mark-on-Push
Some implementations mark a vertex visited when it is pushed rather than when it is popped. That uses less stack space, but it changes which vertex becomes each vertex's parent, and the result is no longer a true depth-first traversal. Take adj = [[1, 2], [2], []]. Recursive DFS discovers 2 from 1, so the parent of 2 is 1. With mark-on-push, vertex 0 marks both 1 and 2 at once, and 2 gets 0 as its parent. Parent pointers that do not match a real DFS will break the cycle reconstruction and edge reasoning in later chapters.
Common Errors
| Error | Symptom | Fix |
|---|---|---|
| No outer loop over all vertices | Misses cycles in unreached regions | Start DFS from every unvisited vertex |
| Marking visited after the recursive call | Infinite recursion on cyclic graphs | Mark on entry, before exploring neighbors |
| Deep recursion in Python | `RecursionError` on long paths | Use an explicit stack, or raise the limit carefully |
| Mutable default argument, such as `def dfs(u, seen=set())` | State leaks between calls | Create the set inside the caller |
| Mark-on-push in iterative DFS | Parent tree differs from true DFS | Mark on pop, or use the iterator-stack form |
| Treating "visited" as "on the path" | False cycles in directed graphs | Track finished vertices separately (later chapter) |
Complexity
With an adjacency list, DFS does constant work per vertex for discovery and finishing. It looks at each adjacency entry once: once per edge in a directed graph, and twice per edge in an undirected graph, because each endpoint stores it. Total time is O(V + E). Extra space is O(V) for the marks, times, and parent array, plus O(V) for the recursion or explicit stack in the worst case. The mark-on-pop iterative version can hold up to O(E) stack entries because of duplicate pushes. With an adjacency matrix, the time becomes O(V²), because every row must be scanned.
Exercise
Run dfs_times by hand on the directed graph adj = [[1], [2], [0, 3], []]. Give the discovery and finish times for each vertex, and say which vertices are on the current path when DFS examines the edge 2 → 0.
Show answer
Discover 0 at 1, 1 at 2, and 2 at 3. Edge 2 → 0 is examined while the path is 0, 1, 2. Vertex 0 is visited and still on the path, so the edge is skipped by plain DFS even though it closes the cycle 0 → 1 → 2 → 0. Then 3 is discovered at 4 and finished at 5. Vertex 2 finishes at 6, vertex 1 at 7, and vertex 0 at 8. The final values are discover = [1, 2, 3, 4] and finish = [8, 7, 6, 5].
Exercise
Two vertices u and v have DFS intervals [3, 10] and [5, 12]. Explain why this cannot happen.
Show answer
The intervals overlap without one containing the other. By the parenthesis property, if v is discovered while u is unfinished (time 5 falls inside [3, 10]), then v is a descendant of u and must finish before u does. So v's finish time would have to be less than 10, not 12.
Exercise
Write a version of dfsorderiterative that uses mark-on-push, run it on adj = [[1, 2], [1, 2], []] from vertex 0 while recording parents, and compare the parent of vertex 2 with what recursive DFS gives.
Show answer
With mark-on-push, popping 0 marks and pushes 2 and then 1 (in reversed order), setting parent[2] = 0 and parent[1] = 0. Popping 1 finds 2 already marked, so parent[2] stays 0. Recursive DFS visits 1 first, discovers 2 from 1, and sets parent[2] = 1. The two trees differ, which shows that mark-on-push is not a true depth-first traversal.