Skip to content
StackDecode
GraphsAnimated

Cycle Detection

DFS finds a back edge to an ancestor.

Time

O(V + E)

Extra space

O(V)

Use it for

Deadlocks, dependency checks.

How it works

  1. Walk the graph with depth-first search, remembering the node we came from (the parent).
  2. If we reach a node that is already visited and is not our parent, we have found a way back to an earlier node: a cycle.
  3. If the search finishes without that happening, the graph has no cycle (it is a forest).
  4. O(V + E).

Watch it run

Loading animation…