Graph Theory37 sections · 1633 units
Open in Course

Cycle Detection - Visualizing

Walking the path

Let's trace a cycle path: ABCAA→B→C→A. Start at A, mark A as Visiting. Go to B, mark B as Visiting. Go to C, mark C as Visiting. C points to A. Check A,it is Visiting. Cycle detected! Return false. The core moment is when C tries to visit A and finds it in state Visiting.

That means A is an ancestor of C in the current DFS path, which proves there is a back edge (cycle). Without the three-state system, you would confuse this with a node visited in a different DFS tree.