Depth-first search follows a branch as far as it can before exploring alternatives. A tree has a built-in parent-child structure, while a general graph can contain cycles and several routes to the same vertex.
Worked example
In a recursive graph traversal, mark a vertex as visited before recursively visiting its unvisited neighbors. On a three-vertex cycle, this rule prevents the last vertex from repeatedly returning to the first. An explicit stack can perform the same exploration without using the language call stack. The order of neighbors can change the traversal order.
What to check
Choose the meaning of visited for the task. A global discovered set is enough for visiting each vertex once. Detecting a directed cycle needs additional information about vertices on the active recursion path. A vertex visited on an earlier completed branch is different from one still on that path. Test a cycle, a shared descendant, and a disconnected component to distinguish these cases.
Continue with the book
Explore the full treatment, worked examples, and exercises in Algorithms Made Simple.
Companion article for Algorithms Made Simple, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.
