Sub topic 8
Discovery and Finish Times
This chapter assumes you can write recursive DFS over an adjacency-list dictionary and that you know how an outer loop over all vertices builds a DFS forest. The earlier chapters recorded only which vertices were visited and in what order. Here you will attach two timestamps to every vertex. Those timestamps let you answer structural questions in constant time, and the next chapters on edge classification, cycle detection, and topological sorting depend on them.
Two Moments in a Vertex's Life
During DFS, each vertex passes through two events:
- Discovery: DFS reaches the vertex for the first time and starts exploring its neighbors.
- Finish: DFS has explored every edge leaving the vertex and returns from it.
A single counter, often called the clock, increases by one at every event. The discovery time d[v] is the clock value when v is discovered. The finish time f[v] is the clock value when v finishes. A graph with V vertices produces 2V events, so the timestamps run from 1 to 2V, and d[v] < f[v] always holds.
Between d[v] and f[v] the vertex is "open": it sits on the recursion stack, and every vertex DFS discovers during that window lies below it in the DFS tree. In the three-color scheme from the cycle-detection chapter, this open window is the time the vertex is gray.
Pre-order and post-order
If you list vertices sorted by discovery time, you get pre-order: a vertex appears before all its descendants. If you sort them by finish time, you get post-order: a vertex appears after all its descendants. The order list from the earlier dfs_recursive function was pre-order. Post-order is the one that powers topological sorting and Kosaraju's algorithm.
Recording Timestamps Recursively
The recursive version adds two clock ticks to the familiar visit function. The first tick happens on entry and the second on exit.
def dfs_times(graph):
discovery = {}
finish = {}
time = 0
def visit(node):
nonlocal time
time += 1
discovery[node] = time # node discovered
for neighbor in graph[node]:
if neighbor not in discovery:
visit(neighbor)
time += 1
finish[node] = time # all edges out of node explored
for node in graph:
if node not in discovery:
visit(node)
return discovery, finish
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["D"],
"D": [],
"E": ["D", "F"],
"F": [],
}
d, f = dfs_times(graph)
for node in graph:
print(node, d[node], f[node])
# A 1 8
# B 2 5
# C 6 7
# D 3 4
# E 9 12
# F 10 11The discovery dictionary doubles as the visited set, because a vertex is in it exactly when it has been discovered. The outer loop makes sure that E and F, which cannot be reached from A, still get timestamps. They start a second tree in the DFS forest.
Here is the trace for this graph:
| Clock | Event | Recursion stack after the event |
|---|---|---|
| 1 | discover A | A |
| 2 | discover B | A, B |
| 3 | discover D | A, B, D |
| 4 | finish D | A, B |
| 5 | finish B | A |
| 6 | discover C | A, C |
| 7 | finish C (D already discovered) | A |
| 8 | finish A | (empty) |
| 9 | discover E | E |
| 10 | discover F (D already discovered) | E, F |
| 11 | finish F | E |
| 12 | finish E | (empty) |
Solid arrows are tree edges, meaning the edges DFS used to discover a new vertex. Dashed arrows are edges DFS examined that pointed to an already-discovered vertex. The next chapter names these edge types.
The Parenthesis Structure
Write (v at time d[v] and v) at time f[v]. The example produces:
(A (B (D D) B) (C C) A) (E (F F) E)
The parentheses always nest correctly. This is the parenthesis theorem: for any two vertices u and v, exactly one of the following holds.
- The intervals
[d[u], f[u]]and[d[v], f[v]]are disjoint, and neither vertex is a descendant of the other. [d[v], f[v]]lies entirely inside[d[u], f[u]], andvis a descendant ofuin the DFS forest.[d[u], f[u]]lies entirely inside[d[v], f[v]], anduis a descendant ofv.
Two intervals never partially overlap. The reason is the call stack. If v is discovered while u is open, then v was pushed on top of u, and v must return before u can.
That gives you a constant-time ancestor test, which comes up in low-link algorithms and tree queries:
def is_proper_ancestor(u, v, d, f):
return d[u] < d[v] and f[v] < f[u]
print(is_proper_ancestor("A", "D", d, f)) # True
print(is_proper_ancestor("C", "D", d, f)) # False: D is reachable from C, but not C's descendant
print(is_proper_ancestor("E", "F", d, f)) # TrueThe C/D case matters. Reachability and descendancy are different things. D can be reached from C, but D was already discovered under B before C started, so in this DFS forest it is not C's descendant.
The white-path theorem
A companion result tells you which vertices become descendants. Vertex v is a descendant of u exactly when, at time d[u], there is a path from u to v that passes only through undiscovered (white) vertices. At time 6, the path from C to D was blocked because D was already discovered, so D did not become C's descendant.
Timestamps Without Recursion
The iterative DFS from the earlier chapter marks a vertex when it is popped and pushes all its neighbors at once. That version has no moment at which a vertex "finishes": by the time its last pushed neighbor is popped, nothing on the stack refers back to the parent. To get finish times without recursion, simulate the call stack itself. Store each vertex together with an iterator over its remaining neighbors.
def dfs_times_iterative(graph):
discovery, finish = {}, {}
time = 0
for root in graph:
if root in discovery:
continue
time += 1
discovery[root] = time
stack = [(root, iter(graph[root]))]
while stack:
node, neighbors = stack[-1]
advanced = False
for neighbor in neighbors: # resumes where it left off
if neighbor not in discovery:
time += 1
discovery[neighbor] = time
stack.append((neighbor, iter(graph[neighbor])))
advanced = True
break
if not advanced: # no unexplored neighbors left
stack.pop()
time += 1
finish[node] = time
return discovery, finish
graph = {
"A": ["B", "C"], "B": ["D"], "C": ["D"],
"D": [], "E": ["D", "F"], "F": [],
}
d, f = dfs_times_iterative(graph)
print([(n, d[n], f[n]) for n in graph])
# [('A', 1, 8), ('B', 2, 5), ('C', 6, 7), ('D', 3, 4), ('E', 9, 12), ('F', 10, 11)]The break pauses the parent's iterator. When the child is popped, the parent's for loop picks up from the next neighbor, which is what returning from a recursive call does. This version matches the recursive output exactly. It also avoids Python's default recursion limit of about 1000 frames, which deep graphs such as long chains will hit.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Recording finish before the neighbor loop | `f[v]` comes right after `d[v]`, so intervals stop nesting | Tick the clock and record finish after the loop |
| Ticking the clock only on discovery | Finish times collide with discovery times | Increment once per event, twice per vertex |
| Using pop-and-mark iterative DFS | No correct place to record finish | Use the iterator-stack version |
| Skipping the outer loop | Unreachable vertices have no timestamps | Loop over all vertices and start a new tree for each undiscovered one |
| Treating `d[u] < d[v]` as "u is an ancestor" | Wrong answers for vertices in sibling subtrees | Check both `d[u] < d[v]` and `f[v] < f[u]` |
Exercises
Exercise
Run dfs_times on {"X": ["Y", "Z"], "Y": ["Z"], "Z": []}. What are the discovery and finish times of X, Y, and Z?
Show answer
X is 1/6, Y is 2/5, and Z is 3/4. DFS goes X, Y, Z, finishes Z at 4 and Y at 5, then skips Z from X because it is already discovered, and finishes X at 6.
Exercise
A DFS reports intervals [2, 7] for vertex u and [5, 9] for vertex v. Is this output possible?
Show answer
No. The intervals partially overlap. By the parenthesis theorem, two intervals are either disjoint or one is nested inside the other, so the timestamping code has a bug.
Exercise
In the example graph, D is reachable from E, but isproperancestor("E", "D", d, f) returns False. Explain using the white-path theorem.
Show answer
At time 9, when E is discovered, D is already finished. No path of undiscovered vertices leads from E to D, so D does not become E's descendant. Its interval [3, 4] is disjoint from E's interval [9, 12].
Exercise
Why can't you record a finish time in the iterative DFS that pops a vertex, marks it, and pushes all its neighbors?
Show answer
That version never returns to a vertex after pushing its neighbors, so no event marks the moment all its descendants are done. The iterator-stack version keeps each vertex on the stack until its neighbors are used up, and that pop is the finish event.