Sub topic 3
Backtracking on Grids, Constraints, and Cost
This chapter assumes you know the choose-explore-unchoose template, pruning, and Big-O notation.
Word Search on a Grid
A grid search starts a path at each cell. From there it steps to one of four neighbours, matching the word one letter at a time. A cell may appear only once in a path. To enforce that, the search overwrites the cell with a marker and restores the letter afterwards.
def exist(board, word):
rows, cols = len(board), len(board[0])
def backtrack(r, c, k):
if k == len(word):
return True
if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[k]:
return False
saved = board[r][c]
board[r][c] = '#' # mark as visited; assumes '#' is not in word
found = any(backtrack(r + dr, c + dc, k + 1)
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)))
board[r][c] = saved
return found
return any(backtrack(r, c, 0) for r in range(rows) for c in range(cols))
grid = [list('ABCE'), list('SFCS'), list('ADEE')]
print(exist(grid, 'ABCCED')) # True
print(exist(grid, 'ABCB')) # FalseN-Queens and Sudoku
N-Queens places one queen per row, so the choice at each level is a column. Three sets record attacked lines: columns, row - col diagonals, and row + col anti-diagonals. Each safety check takes constant time, so an attacked square is rejected without ever being explored. For n = 8 there are 92 solutions.
Sudoku is a constraint satisfaction problem (CSP). Each empty cell is a variable, its domain is the digits 1 to 9, and the constraints say a digit cannot repeat in a row, column, or 3×3 box. The solver puts a valid digit in an empty cell and recurses. If no digit fits a cell, it resets the cell to 0 and returns False, and the caller tries its next digit.
Cost of Backtracking
Time is roughly (number of nodes in the tree) × (work per node). Space is the recursion depth plus the current path.
| Problem | Time | Extra space |
|---|---|---|
| Subsets | O(n · 2ⁿ) | O(n) |
| Permutations | O(n · n!) | O(n) |
| Word search | O(R·C · 3ᴸ) | O(L) |
| N-Queens | under O(n!) | O(n) |
The word-search bound uses 3 rather than 4 because a step never goes back into the cell it just left. Pruning does not change the worst-case bound, but it often removes most of the tree in practice.
Ordering Heuristics and Forward Checking
The minimum remaining values (MRV) heuristic fills the variable with the fewest legal values first, so failures show up near the root of the tree. Forward checking works on the other side of each choice: after a value is assigned, that value is removed from the domains of neighbouring cells. If any domain becomes empty, the search backtracks at once.
Backtracking Without Recursion
You can replace recursion with an explicit stack of frames. Each frame holds the current depth and the index of the next choice to try. Popping a frame plays the role of unchoose. This avoids Python's recursion limit when the tree is deep.
When Not to Backtrack
- Dynamic programming: use it when subproblems overlap and you only need a count or an optimum, not every solution. Counting subsets that reach a target sum is one example.
- Branch and bound: use it for optimization problems. It prunes any branch whose best possible score cannot beat the best solution found so far.
- Plain backtracking: use it when you must list every solution or find any one solution that satisfies the constraints.
Exercise
In N-Queens, why are both row - col and row + col needed to describe diagonals?
Show answer
Cells on one down-right diagonal share the same row - col value. Cells on one down-left diagonal share the same row + col value. Each set tracks one direction, and together they cover every diagonal attack.
Exercise
You need the number of ways to make change for 500 using coins of 1, 5, and 25. Should you use backtracking or dynamic programming, and why?
Show answer
Use dynamic programming. You need only a count, and the remaining-amount subproblems repeat many times. Backtracking would enumerate every combination separately.