LOGBOOK

HELP

Quiz Entry - updated: 2026.11.27

How does DFS find a cycle, and how is the cycle read off the stack?

Run DFS with a stack S of the current route, as for path finding, pushing each edge before checking its far end. The first back edge (v, w) closes a cycle: w is an ancestor of v and therefore still on the stack, so popping S down to w and collecting the popped items in a new stack T yields the cycle from w through v and back over the back edge to w.

cycleDFS from A: after A-B and B-C, the back edge C-A closes the cycle; the stack S is popped down to A into a stack T

* Popping from S into T reverses the order, so T reads from w round to the back edge. *

In the example DFS starts at A, follows A–B and B–C, and at C meets the edge C–A, whose far end A is already visited. The stack then holds A, A–B, B, B–C, C, C–A. Popping down to A moves these six items into T, which, read from its top, gives A, A–B, B, B–C, C, C–A: the cycle A, B, C, A.

The reason w is guaranteed to be on the stack: in an undirected graph DFS produces back edges only to ancestors, the vertices whose calls are still open, and those are exactly the vertices on S.

Why pop down to w instead of handing over all of S? Here the cycle happens to start at the start vertex. In general the stack also holds the way in: had DFS started at a vertex 1 and come to A via 1–2 and 2–A, the stack would begin 1, 1–2, 2, 2–A, A, … . Popping only down to w takes out exactly the cycle and leaves the way in behind.

Finding a cycle is quick. Until the first back edge, every edge DFS examines is a discovery edge, or one seen again from its other end, and there are at most n − 1 discovery edges; so the search stops after $O(n)$ edge checks, however many edges the graph has.

If a DFS of the whole graph meets no back edge at all, the graph has no cycle: every component is a tree, and the graph is a forest. BFS can make the same test, with a cross edge in place of the back edge.

Go deeper:

From Quiz: ADS / Graph Traversals: Depth-First and Breadth-First Search | Updated: Nov 27, 2026