Stamps on the way down
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.
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.
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.
Four kinds of 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'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.
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.
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.
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.
What the times prove
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.
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).
The same thing in Python
# step 1/10 · A directed graph
adj = {
"A": ["B", "D"],
"B": ["C"],
"C": ["A", "D"],
"D": [],
"E": ["C"],
}
>>> adj["C"] # C's edges lead to A and D
['A', 'D']
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. 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.