How depth-first search works
dfs(node) returns straight away if the node was already visited. Otherwise it marks and records the node, then calls itself on each neighbour in turn. A call only returns once everything reachable from it has been explored, and that is what produces the backtracking.
The example is a small directed graph: A → B, C; B → D; C → E; D → F; E → F. From A it visits A, B, D, F, backs all the way up to A, then goes down C to E — where F has already been visited.
What to watch for when it runs
- The call stack holds the current path from A, so its height is how deep the search has gone.
- When a branch is exhausted, frames pop one at a time — that is the backtracking, made visible.
- Compare the visit order with breadth-first search: one path to the end first, not one layer at a time.
Time and space complexity
- Time
- O(V + E)
- Space
- O(V)
Every vertex is visited once and every edge followed once. In the worst case — a long chain — the recursion is V calls deep.