Recursion & Backtracking
Recursion is when a function solves a problem by calling itself on smaller versions of the same problem. Backtracking is a recursive search strategy: build a solution one choice at a time, and as soon as a partial solution can't possibly work, undo the last choice and try the next one.
Many algorithms in this course are recursive (merge sort, quick sort, tree traversals, DFS). This lesson looks at recursion itself and then at backtracking, which solves puzzles and combinatorial search problems.
Anatomy of a recursive function
Every correct recursive function has:
- A base case that is answered directly, without recursion.
- A recursive case that calls the function on a smaller input, so the base case is eventually reached.
def countdown(n):
if n == 0: # base case
print("liftoff!")
return
print(n)
countdown(n - 1) # smaller problem
def total(values):
if not values: # base case: the sum of nothing is 0
return 0
return values[0] + total(values[1:])
countdown(3)
print(total([4, 8, 15, 16, 23, 42]))3
2
1
liftoff!
108
The call stack
Each call gets its own frame on the call stack with its own local variables. The frames pile up until a base case returns, then unwind in reverse order. Indentation makes this visible:
def power(base, exp, depth=0):
pad = " " * depth
print(f"{pad}power({base}, {exp})")
if exp == 0:
result = 1
elif exp % 2 == 0:
half = power(base, exp // 2, depth + 1)
result = half * half # square the half result
else:
result = base * power(base, exp - 1, depth + 1)
print(f"{pad}= {result}")
return result
power(3, 5)power(3, 5)
power(3, 4)
power(3, 2)
power(3, 1)
power(3, 0)
= 1
= 3
= 9
= 81
= 243
This "fast exponentiation" needs only O(log n) multiplications, because even exponents are halved.
Note: Python limits recursion depth (about 1000 frames by default) and raises
RecursionErrorbeyond it. Deep recursions like a linked list of 100,000 nodes should be written with loops.
Backtracking: generate all subsets
To list all subsets of a set, decide for each element: include it or not. That's a binary tree of choices with 2ⁿ leaves. The recursion explores it depth-first, and the "undo" step (pop) restores the state before trying the other branch:
def subsets(items):
result, current = [], []
def choose(i):
if i == len(items):
result.append(list(current))
return
current.append(items[i]) # choice 1: include items[i]
choose(i + 1)
current.pop() # undo the choice
choose(i + 1) # choice 2: exclude items[i]
choose(0)
return result
print(subsets(["a", "b", "c"]))[['a', 'b', 'c'], ['a', 'b'], ['a', 'c'], ['a'], ['b', 'c'], ['b'], ['c'], []]
Pruning: subset sum
Backtracking becomes powerful when we can prune: stop exploring a branch as soon as it can't lead to a solution. Find all combinations of prices that add up exactly to a budget; once the running total exceeds the budget, there is no point continuing:
def combos(prices, budget):
prices = sorted(prices)
found, picked, explored = [], [], 0
def search(start, remaining):
nonlocal explored
explored += 1
if remaining == 0:
found.append(list(picked))
return
for i in range(start, len(prices)):
if prices[i] > remaining:
break # prune: sorted, so the rest are too big too
picked.append(prices[i])
search(i + 1, remaining - prices[i])
picked.pop()
search(0, budget)
return found, explored
found, explored = combos([8, 3, 5, 12, 7, 2, 10], 15)
print(found)
print("calls:", explored, "instead of", 2 ** 7, "subsets")[[2, 3, 10], [2, 5, 8], [3, 5, 7], [3, 12], [5, 10], [7, 8]]
calls: 30 instead of 128 subsets
The N-Queens puzzle
Place n queens on an n × n chessboard so that no two attack each other (same row, column or diagonal). Backtracking places one queen per row and only tries columns that are not attacked:
def solve_queens(n):
cols, diag1, diag2 = set(), set(), set()
placement, solutions = [], []
def place(row):
if row == n:
solutions.append(list(placement))
return
for col in range(n):
if col in cols or (row - col) in diag1 or (row + col) in diag2:
continue # attacked: prune
cols.add(col); diag1.add(row - col); diag2.add(row + col)
placement.append(col)
place(row + 1)
placement.pop() # backtrack
cols.remove(col); diag1.remove(row - col); diag2.remove(row + col)
place(0)
return solutions
solutions = solve_queens(6)
print(len(solutions), "solutions for 6 queens; the first one:")
for col in solutions[0]:
print(" ".join("Q" if c == col else "." for c in range(6)))
print("solutions for n = 4..8:", [len(solve_queens(n)) for n in range(4, 9)])4 solutions for 6 queens; the first one:
. Q . . . .
. . . Q . .
. . . . . Q
Q . . . . .
. . Q . . .
. . . . Q .
solutions for n = 4..8: [2, 10, 4, 40, 92]
Two squares are on the same diagonal when row - col (one direction) or row + col (the other) is equal, which makes the attack check O(1).
Escaping a maze
A maze is a graph, and finding a way out is a DFS with backtracking: mark the cell as part of the path, try each direction, and unmark it if no direction leads to the exit.
maze = [
"S.#....",
".##.##.",
"...#...",
"#......",
"..##.#E",
]
rows, cols = len(maze), len(maze[0])
path = []
def walk(r, c, seen):
if not (0 <= r < rows and 0 <= c < cols) or maze[r][c] == "#" or (r, c) in seen:
return False
seen.add((r, c))
path.append((r, c))
if maze[r][c] == "E":
return True
for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)): # right, down, left, up
if walk(r + dr, c + dc, seen):
return True
path.pop() # dead end: backtrack
return False
walk(0, 0, set())
on_path = set(path)
for r in range(rows):
print("".join("*" if (r, c) in on_path and maze[r][c] == "." else maze[r][c] for c in range(cols)))
print("path length:", len(path) - 1, "steps")S.#....
*##.##.
***#...
#.*****
..##.#E
path length: 10 steps
Summary
| Problem | Choices per step | Pruning | Size of search |
|---|---|---|---|
| All subsets | include / exclude | none | 2ⁿ |
| Subset sum | next item to add | stop when over budget | much less than 2ⁿ in practice |
| N-Queens | column for this row | skip attacked columns | far less than nⁿ |
| Maze | direction | walls, visited cells | at most every cell |
Backtracking is still exponential in the worst case, but good pruning often makes it fast enough. When the same partial states repeat, add memoization and you have dynamic programming.
Test yourself
What happens if a recursive function has no reachable base case?
- It returns None
- It recurses until Python raises RecursionError
- It runs in O(1)
- It becomes a loop automatically
What does the "backtrack" step do?
- Restarts the whole search
- Undoes the last choice so the next alternative can be tried
- Sorts the input
- Stores the result in a cache
How many subsets does a set of 5 elements have?
- 5
- 10
- 25
- 32