Trees and graphs · Intermediate
Depth-first search and backtracking
Go as deep as possible before turning back; with choose, explore and undo, the same recursion enumerates subsets, permutations and constrained placements.
On this page
The idea
DFS follows one path until it cannot continue, then returns to the latest branching point. On a graph it finds connected components, detects cycles and visits everything reachable. The call stack (or an explicit stack) remembers where to resume.
Backtracking is DFS over a tree of decisions that is never built explicitly. At each level you choose an option, recurse, then undo the choice so the shared state is clean for the next option. Pruning, stopping a branch as soon as it cannot lead to a valid answer, is what makes it practical.
How to recognise it
- Generate all subsets, permutations, combinations or placements that satisfy constraints.
- Count or list connected regions (islands, components) or detect a cycle.
- Small input bounds (n ≤ 20 or so) that hint at exponential search.
- The answer depends on the whole path taken, not only on its length.
When not to use it
- Overlapping subproblems with the same state reappear many times: memoise (dynamic programming) instead of re-exploring.
- You need shortest paths in an unweighted graph: DFS finds a path, not the shortest one.
- Recursion depth could reach the input size on large inputs: switch to an explicit stack to avoid stack overflow.
Template
Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.
# Graph DFS
def dfs(u):
visited.add(u)
for v in neighbours(u):
if v not in visited: dfs(v)
# Backtracking: all subsets of items
def backtrack(i, chosen):
if i == len(items):
output(copy(chosen)); return
backtrack(i + 1, chosen) # skip items[i]
chosen.push(items[i]) # choose
backtrack(i + 1, chosen) # explore
chosen.pop() # undo
backtrack(0, [])- Copy the partial answer when you record it; recording the shared list records a list that will keep changing.
- Prune before recursing: check constraints at the moment of choosing.
Complexity
Time O(V + E) for graph DFS; O(2ⁿ) subsets, O(n!) permutations, extra space O(depth). Backtracking cost is the number of nodes in the decision tree times the work per node; pruning lowers the constant or the exponent in practice but rarely the worst case.
Worked examples
Subsets of [a, b]
Skip a, skip b → []. Skip a, take b → [b]. Take a, skip b → [a]. Take a, take b → [a, b]. Four leaves for two items: 2ⁿ.
Pitfalls
- Forgetting the undo step, so choices leak into sibling branches.
- Not marking visited nodes in a graph with cycles, causing infinite recursion.
- Deep recursion on large grids exceeding the default stack size.
Practise it
Solved problems with hints, a correctness argument and four tested implementations:
- ProblemCount the separate land masses· intermediate · O(rows · columns)
Learn the foundations
Lessons
- ModuleM24 BFS and DFS· intermediate
- ModuleM31 Backtracking· intermediate
- ModuleM11 Recursion· intermediate
- VisualizerTree traversal· Θ(n)
- Complexity exerciseGenerating every subset· Θ(n · 2ⁿ) including copying; 2ⁿ outputs
- Complexity exerciseGenerating every permutation· Θ(n · n!) with output
- Complexity exerciseRecursion that peels off one element· Θ(n)
Related patterns
- PatternBreadth-first search and level order· O(V + E)
- PatternDynamic programming (1D and 2D)· O(states × transitions)
- PatternTopological ordering· O(V + E)
References
dsa.pattern.dfs-backtracking · version 1