Sub topic 3
DFS Discovery and Finish Times
This chapter assumes you can read Python, know how recursive depth-first search (DFS) works on an adjacency list, and are comfortable with the idea of reachability in a directed graph from the previous chapters. Here we add one thing to DFS: a clock. Recording when each vertex is first reached and when it is fully explored is the basis of the timing arguments behind Kosaraju's algorithm and, in a modified form, Tarjan's algorithm.
The Clock Inside DFS
DFS keeps a single global counter called time. It increases by one at two moments for each vertex u:
- Discovery time
disc[u]is the clock value when DFS first reachesu. - Finish time
fin[u]is the clock value when DFS has explored every outgoing edge ofuand is about to return.
Between those two moments, u sits on the recursion stack. A standard way to track this is with three colors:
| Color | Meaning | Time window |
|---|---|---|
| White | Not yet discovered | before `disc[u]` |
| Gray | Discovered, still on the recursion stack | between `disc[u]` and `fin[u]` |
| Black | Finished, all descendants explored | after `fin[u]` |
With n vertices, the clock ticks exactly 2n times. Every value from 1 to 2n is used once, and disc[u] < fin[u] always holds.
Implementation
The code below records both timestamps, the colors, and the list of vertices in the order they finish. That last list is what Kosaraju's first pass produces.
def dfs_timestamps(n, adj):
WHITE, GRAY, BLACK = 0, 1, 2
color = [WHITE] * n
disc = [0] * n
fin = [0] * n
parent = [None] * n
finish_order = []
time = 0
def visit(u):
nonlocal time
time += 1
disc[u] = time
color[u] = GRAY
for v in adj[u]:
if color[v] == WHITE:
parent[v] = u
visit(v)
time += 1
fin[u] = time
color[u] = BLACK
finish_order.append(u)
for u in range(n):
if color[u] == WHITE:
visit(u)
return disc, fin, parent, finish_order
# Example graph with SCCs {0,1,2}, {3,4,5}, {6,7}
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]
disc, fin, parent, order = dfs_timestamps(8, adj)
print(disc) # [1, 2, 3, 4, 5, 6, 13, 14]
print(fin) # [12, 11, 10, 9, 8, 7, 16, 15]
print(parent) # [None, 0, 1, 2, 3, 4, None, 6]
print(order) # [5, 4, 3, 2, 1, 0, 7, 6]Tracing the example
DFS starts at 0 and walks the chain 0 → 1 → 2. At vertex 2 the edge back to 0 is ignored because 0 is gray. DFS then continues 2 → 3 → 4 → 5. Vertex 5's only edge points to the gray vertex 3, so 5 finishes first at time 7. The stack then unwinds: 4, 3, 2, 1, and 0 finish at times 8 through 12.
Vertices 6 and 7 are not reachable from 0, so the outer loop starts a second DFS tree at 6. The edge 6 → 5 is skipped because 5 is already black. Vertex 7 is discovered at 14, and its edge back to 6 is skipped because 6 is gray.
Solid arrows are tree edges, meaning the edges DFS followed to discover a white vertex. Dotted arrows are all other edges. The next chapter names these other edge types formally.
The Parenthesis Theorem
Write [ at each discovery and ] at each finish. The example produces this sequence:
[0 [1 [2 [3 [4 [5 5] 4] 3] 2] 1] 0] [6 [7 7] 6]
The brackets are always properly nested. This is the parenthesis theorem: for any two vertices u and v, exactly one of these holds.
- The intervals
[disc[u], fin[u]]and[disc[v], fin[v]]are disjoint. Neither vertex is a descendant of the other in the DFS forest. u's interval containsv's. Thenvis a descendant ofu.v's interval containsu's. Thenuis a descendant ofv.
Partial overlap like disc[u] < disc[v] < fin[u] < fin[v] can never happen. The reason is the recursion stack. If v is discovered while u is gray, then v is pushed above u, and v has to be popped (finished) before u can be.
You can check the theorem mechanically:
def check_parenthesis(disc, fin, parent):
n = len(disc)
def is_descendant(v, u):
while v is not None:
if v == u:
return True
v = parent[v]
return False
for u in range(n):
for v in range(n):
if u == v:
continue
nested = disc[u] < disc[v] and fin[v] < fin[u]
disjoint = fin[u] < disc[v] or fin[v] < disc[u]
reverse_nested = disc[v] < disc[u] and fin[u] < fin[v]
assert nested or disjoint or reverse_nested
assert nested == is_descendant(v, u)
return True
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]
disc, fin, parent, _ = dfs_timestamps(8, adj)
print(check_parenthesis(disc, fin, parent)) # TrueThe White-Path Theorem
The parenthesis theorem tells you how to read the DFS forest from the timestamps. The white-path theorem tells you which vertices end up below u:
v becomes a descendant of u exactly when, at time disc[u], there is a path from u to v that uses only white vertices.
The word "white" matters. In the example, 5 is reachable from 6, but 5 is not a descendant of 6. When 6 was discovered, 5 was already black, so no all-white path existed. Reachability alone does not determine the tree. What has already been visited also matters.
This theorem is the key to SCCs. When DFS discovers the first vertex of a strongly connected component, every other vertex in that component is still white and reachable along a path inside the component. So the whole component ends up in the subtree of that first vertex.
Edges and Finish Times
The most useful single fact about finish times concerns an edge u → v at the moment DFS examines it from u:
| State of `v` | What it means | Relation of finish times |
|---|---|---|
| White | `v` becomes a descendant of `u` | `fin[v] < fin[u]` |
| Black | `v` already finished | `fin[v] < fin[u]` |
| Gray | `v` is an ancestor of `u` on the stack | `fin[v] > fin[u]` |
Only the gray case reverses the order, and that case means the graph has a cycle through u and v. This gives two consequences:
- In a DAG, decreasing finish time is a topological order. No edge points to a gray vertex, so every edge
u → vhasfin[u] > fin[v]. - In a general graph, edges that go against the finish order always lie on cycles. Cycles are what SCCs group together. A later chapter extends this to whole components. If component C has an edge into component C′, the largest finish time in C is larger than the largest finish time in C′. Kosaraju's algorithm is built on that fact.
Edge Cases and Common Errors
- Root order and adjacency order change the numbers. A different starting vertex or neighbor order produces different timestamps and a different forest. The theorems above hold for every run. Do not write tests that depend on specific timestamp values unless you fix the iteration order.
- Self-loops. The edge
u → ufindsugray. That is correct: a self-loop is a cycle of length 1. - Parallel edges. The second copy finds
vgray or black and is skipped. Timestamps are unaffected. - Isolated vertices. They get consecutive times, such as
disc = 17, fin = 18, and form a one-vertex tree. - Forgetting the outer loop. If you call
visit(0)only, vertices unreachable from 0 never receive timestamps. Every SCC algorithm needs the loop over all vertices. - Using a visited boolean when you need gray versus black. A single boolean cannot tell an ancestor on the stack apart from a finished vertex. That distinction drives cycle detection. Tarjan's algorithm keeps a separate
on_stackarray for the same reason. - Separate counters. Some implementations use one counter for discovery and another for finish. That still gives a valid finish order, but the parenthesis checks above stop working. Use one shared clock if you want the interval properties.
- Recursion depth. CPython's default recursion limit is 1000. A path graph with 10,000 vertices raises
RecursionError. A later chapter converts DFS to an iterative form.
What the Later Algorithms Use
| Algorithm | What it takes from this chapter |
|---|---|
| Kosaraju | The full finish order (`finish_order`), processed in reverse |
| Tarjan | Discovery indices only, plus the gray-versus-black distinction via `on_stack` |
| Topological sort | Decreasing finish time on a DAG |
Exercise
Run dfstimestamps by hand on adj = [[1, 2], [3], [3], []]. Give disc, fin, and finishorder.
Show answer
DFS visits 0 (disc 1), then 1 (disc 2), then 3 (disc 3, fin 4). Vertex 1 finishes at 5. Back at 0, it visits 2 (disc 6). Vertex 3 is black, so 2 finishes at 7 and 0 finishes at 8. disc = [1, 2, 6, 3], fin = [8, 5, 7, 4], finish_order = [3, 1, 2, 0]. Reversed, 0, 2, 1, 3 is a valid topological order.
Exercise
After a full DFS, you find an edge u → v with fin[v] > fin[u]. What can you conclude about v, and about the graph?
Show answer
When the edge was examined, v could not have been white (it would finish before u) or black (it already finished before u). So v was gray, which means v is an ancestor of u in the DFS forest. The tree path from v to u plus the edge u → v forms a cycle, so u and v are in the same SCC.
Exercise
In the example graph, 5 is reachable from 6, yet 5 is not a descendant of 6. Which theorem explains this, and what would change if the outer loop started at vertex 6 instead of 0?
Show answer
The white-path theorem explains it. When 6 was discovered, 5 was already black, so no all-white path from 6 to 5 existed. If DFS started at 6, then 5, 3, and 4 would be white and reachable, so they would become descendants of 6. The component {6, 7} would then finish last, and its finish time would be larger than that of {3, 4, 5}, as the component finish-time property predicts.