DFS in depth: discovery times and cycle detection
About this lesson
Depth-first search becomes far more useful once it carries a clock. Run it on a small directed graph and stamp each node twice: when its call starts (discovery) and when it ends (finish). The stamps show which calls are still open, sort every edge into tree, back, forward or cross, and give a clean test for cycles: a directed graph has one exactly when DFS finds a back edge. The Software lessons "Graphs" and "Graph search: BFS and DFS" and the Maths lesson on graph theory introduce the graphs and the plain search used here.
A directed graph
Each edge here is one-way: A→B lets you go from A to B, not back. Five nodes, six edges. Depth-first search (DFS) follows edges as deep as it can, then backs up. We will time every move it makes.
adj = {
"A": ["B", "D"],
"B": ["C"],
"C": ["A", "D"],
"D": [],
"E": ["C"],
}
>>> adj["C"] # C's edges lead to A and D
['A', 'D']Read the lesson step by step
A directed graph
Each edge here is one-way: A→B lets you go from A to B, not back. Five nodes, six edges. Depth-first search (DFS) follows edges as deep as it can, then backs up. We will time every move it makes.
adj = { "A": ["B", "D"], "B": ["C"], "C": ["A", "D"], "D": [], "E": ["C"], } >>> adj["C"] # C's edges lead to A and D ['A', 'D']Discover A at time 1
A clock counts up by 1 at every start and every end. visit(A) runs first and stamps A's discovery time: d[A] = 1. A turns gray, meaning found but not finished. Its call waits on the call stack.
clock = count(1) # 1, 2, 3, ... visit("A") d["A"] = next(clock) # 1 colour = white if u not in d gray if u in d but not in f black if u in f call stack: visit(A)Dive deeper: B, then C
A's first edge leads to B. B is white, never seen, so visit(B) starts: d[B] = 2. B→C works the same way: d[C] = 3. These are tree edges. The gray nodes A, B and C are exactly the call stack.
A→B B is white → tree edge, visit(B) d["B"] = 2 B→C C is white → tree edge, visit(C) d["C"] = 3 call stack: visit(A) visit(B) visit(C) gray: A B CC→A is a back edge
C looks along its edge to A. A is gray: its call is still on the stack, so A is an ancestor of C. An edge back to an ancestor closes a loop, A→B→C→A. That is a cycle, and the lamp turns on.
C→A "A" in d → seen "A" not in f → still open: gray back.append(("C", "A")) path on the stack: A → B → C plus the edge C → A: a cycle A→B→C→A >>> back [('C', 'A')]D finishes first
C's next edge leads to D, which is white: another tree edge, d[D] = 4. D has no edges going out, so its call ends at once: f[D] = 5, its finish time. D turns black, done for good.
C→D D is white → tree edge, visit(D) d["D"] = 4 for v in adj["D"]: # [] : nothing to do f["D"] = next(clock) # 5 call stack: visit(A) visit(B) visit(C) black: DBack up: C, then B
With D done, C has no edges left, so C finishes at 6 and its call leaves the stack. B had only one edge, so B finishes at 7. Calls finish in the reverse order they started.
f["C"] = 6 visit(C) returns f["B"] = 7 visit(B) returns call stack: visit(A) black: D C B (finish order so far)A→D is a forward edge
Back in A, the next edge leads to D. D is black, and d[A] = 1 is less than d[D] = 4: D was found inside A's call, so D is a descendant. A forward edge, no loop. A finishes at 8.
A→D "D" in f → black: nothing to do d["A"] = 1 < d["D"] = 4 → D is a descendant of A: forward edge f["A"] = 8 visit(A) returns call stack: (empty)E→C is a cross edge
The outer loop finds E still white, so a new search starts there: d[E] = 9. E→C points at black C, and d[C] = 3 is less than 9: C finished before E began. A cross edge. f[E] = 10.
for u in adj: # A B C D done visit("E") # d["E"] = 9 E→C "C" in f → black d["E"] = 9 > d["C"] = 3 → C finished before E began: cross edge f["E"] = 10Times nest like brackets
Write ( at each discovery and ) at each finish: (A (B (C (D D) C) B) A) (E E). D's span, 4 to 5, sits inside C's 3 to 6, inside B's, inside A's. Spans nest or stay apart, never half-overlap.
>>> d {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 9} >>> f {'D': 5, 'C': 6, 'B': 7, 'A': 8, 'E': 10} (A (B (C (D D) C) B) A) (E E) v is a descendant of u ⇔ d[u] < d[v] < f[v] < f[u]A cycle means a back edge
A directed graph has a cycle exactly when DFS finds a back edge. Delete C→A and run again: every time stays the same, but no edge reaches a gray node, so the lamp stays 0. Cost: O(V + E).
adj["C"] = ["D"] # C→A deleted >>> back [] # no back edge: no cycle each node: entered once, left once each edge: looked at once V + E = 5 + 6: time O(V + E)
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01While DFS is running, which nodes are gray?
A node turns gray when visit(u) starts (d[u] is set) and black when it returns (f[u] is set). In between its call is open, so the gray nodes are exactly the call stack.
02DFS is inside visit(u) and looks at the edge u→v. v is gray. What kind of edge is this?
A gray v is still on the stack, so it is an ancestor of u. The edge points back up the current path, which closes a loop: a back edge.
03In the lesson's run, d[A] = 1, f[A] = 8, d[D] = 4, f[D] = 5. When A looks at A→D, D is already black. Why is A→D a forward edge and not a cross edge?
D's span 4 to 5 sits inside A's span 1 to 8, so D is a descendant of A. An edge to a black descendant is a forward edge; an edge to a black node outside your own span (like E→C, with 3 < 9) is a cross edge.
04Which of these discovery/finish spans can never happen for two nodes in the same DFS run?
Spans either nest (one call runs inside the other) or are disjoint. [2, 5] and [4, 7] half-overlap: the second call would start inside the first and end after it, which a call stack cannot do.
05You delete the edge C→A from the lesson's graph and run DFS again. What happens?
C→A only ever found a gray node; it never started a call. Without it every stamp is the same, but no edge reaches a gray node, and with no back edge the directed graph has no cycle.
Glossary
- Directed graph
- A graph whose edges are one-way: u→v lets you go from u to v but not back.
- Discovery time d[u]
- The clock value when the call visit(u) starts.
- Finish time f[u]
- The clock value when visit(u) returns, after all its edges are handled.
- White, gray, black
- Not found yet; found but its call still running (on the stack); finished.
- Tree edge
- An edge DFS follows to a white node, starting a new call.
- Back edge
- An edge to a gray node: an ancestor still on the stack. It closes a cycle.
- Forward and cross edges
- Edges to a black node: forward if it is a descendant (d[u] < d[v]), cross if it finished before u started.
- Parenthesis theorem
- In one DFS run, any two nodes' [d, f] spans are either nested or disjoint, never half-overlapping.
Notes and sources
- CLRS keeps a separate colour per node: white, gray, black. The code here reads the colour from the two dictionaries instead: not in d is white, in d but not in f is gray, in f is black.
- The times depend on the order the edges are tried; here, list order. Another order can change which edges count as forward or cross, but a graph with a cycle always gives at least one back edge.
- In an undirected graph every edge works both ways, so DFS finds only tree and back edges. There, a cycle is an edge to a seen node other than the one you just came from.
- Python limits how deep calls can nest (see sys.getrecursionlimit()). For a graph with a very long path, keep the stack yourself in a list instead of recursing.
- Each node is entered once and left once, and each edge is looked at once, so the whole run takes O(V + E) time, where V counts nodes and E counts edges.
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §20.3 Depth-first search and §20.4
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 10: Depth-First Search
- Sedgewick and Wayne, Algorithms 4th ed., §4.2 Directed graphs
- Sedgewick and Wayne, DirectedCycle.java (cycle detection with onStack[])
- Python documentation: itertools.count
- Python documentation: sys.getrecursionlimit
Quiz Unlocks after the last step.