EB01cycle?ACDstackbottomtop12345678910clock1def visit(u):2 d[u] = next(clock)3 for v in adj[u]:4 if v not in d:5 visit(v)6 elif v not in f:7 back.append((u, v))8 f[u] = next(clock)TFTBTCABCDEwhite
Nodes: lens white → gray → black; the front shows discovery/finishEdges: T tree (mint), B back (red), F forward (violet), C cross (orange)Call stack and clock tape: ( at a discovery, ) at a finishDepth-first search with a clock: each call stamps its node with a discovery time when it starts and a finish time when it ends, so a node is white, then gray while its call is on the stack, then black. Each edge is sorted by what it finds at its far end: a white node (tree edge), a gray ancestor (back edge), or a black node found earlier inside this call (forward) or outside it (cross). A back edge closes a loop: a directed graph has a cycle exactly when DFS finds one.

Stamps on the way down

  1. 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.

Four kinds of edge

What the times prove

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.