Cycle Detection

Identifying cycles in graphs using DFS traversal and recursive stack tracking.

What is Cycle Detection?

Cycle Detection is the task of finding closed loops in graphs. In directed graphs, cycles are detected during a Depth-First Search (DFS) traversal by identifying 'back-edges'. A back-edge is an edge that points from the current vertex to an ancestor vertex that is still active in the current recursion stack.

Key Characteristics:

  • Detects recursive loops in directed networks.
  • Maintains recursion stack state.
  • Distinguishes between back-edges, forward-edges, and cross-edges.
  • Essential for deadlock detection and compiler compilation orders.

Complexity Analysis

Avg Time Complexity: O(V + E) where V is vertices and E is edges
Space Complexity: O(V) visitor state maps
Best Case: O(1) (cycle detected at first node)
Worst Case: O(V + E) (acyclic graph)

How it Works Step-by-Step

  1. State Init: Maintain arrays/maps for visited (fully processed) and recursion_stack (active in current DFS path).
  2. Loop All Nodes: For each unvisited node, run DFS.
  3. Push Recursion: Mark current node as visited and add to recursion_stack.
  4. Evaluate Neighbors: For each neighbor v, if v is in recursion_stack, a cycle is detected.
  5. Recurse: If neighbor v is not visited, recursively call DFS on v. If that returns true, propagate cycle detection.
  6. Backtrack: Remove current node from recursion_stack and return false.

Code Implementation

Worked Trace Example

Directed graph: A->B, B->C, C->A:
1. DFS(A): mark A as visited & active. Stack = {A}.
2. Visit B: DFS(B): mark B as visited & active. Stack = {A, B}.
3. Visit C: DFS(C): mark C as visited & active. Stack = {A, B, C}.
4. From C: Neighbor A is already in the recursion stack! Cycle detected.
Result: Cycle detected (A->B->C->A).

Ready to Understand Cycle Detection Visually?

Don't just read about it. Launch our interactive, premium algorithm visualizer to step through calculations in real-time.

Launch Cycle Detection Visualizer →