What's happening?
- Visit the start node and mark it visited.
- Go to its first unvisited neighbour and repeat from there — deeper and deeper.
- When a node has no unvisited neighbours, back up one level and try the next option.
Complexity
- Time
- O(V + E) — every node and edge once
- Space
- O(V) for the call stack in the worst case
Where you'll meet it
Maze and puzzle solving (backtracking), detecting cycles, topological sort for build systems and course prerequisites, and finding connected components.
Common mistake
Recursing on very deep graphs without limit — the call stack overflows. Use an explicit stack for huge graphs.
FAQ
Does DFS find the shortest path?
No. It finds a path, not necessarily the shortest — use BFS (equal costs) or Dijkstra (weights).
Recursive or iterative DFS?
Both work. Recursion is shorter to write; an explicit stack avoids stack-overflow on deep graphs.
Why did DFS and BFS visit the same order from A here?
On this graph they happen to — but look at the trees they build: BFS spreads out from A, DFS makes one long chain.