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
  1. The idea
  2. How to recognise it
  3. When not to use it
  4. Template
  5. Complexity
  6. Worked examples
  7. Pitfalls
  8. Practise it
  9. Learn the foundations
  10. References

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:

Learn the foundations

Related patterns

References

dsa.pattern.dfs-backtracking · version 1