Practice Discrete Math

Algorithms / Graph Cycle Detection

Least You Need to Know: Cycle Detection in Directed and Undirected Graphs

Cycle detection depends on graph type. In undirected graphs, you must ignore the edge back to the parent. In directed graphs, the key signal is whether DFS re-enters a node that is still on the current recursion path.

The least you need to know

Key notation

parent the previous node in undirected DFS
recursion stack nodes currently active on the DFS path
back edge edge to an ancestor on the current DFS path

Tiny worked example

  • In a directed graph, DFS marks nodes as unvisited, active, or finished.
  • When DFS follows an edge to an active node, it has found a cycle on the current path.
  • In an undirected graph, that same check must ignore the edge back to the parent.

Common mistakes

How to recognize this kind of problem

Start practice