Sub topic 10
Backtracking on Grids: Word Search
This chapter assumes you already know the choose-explore-unchoose template and how to restore mutable state after a recursive call. You should also be comfortable indexing a two-dimensional list in Python.
The Problem
You are given a grid of letters and a word. Can you trace the word by moving between cells that touch horizontally or vertically, without using any cell twice in the same path?
In this search, each node of the state-space tree is a pair: a current cell and the number of letters matched so far. A choice is one of the four neighbouring cells. A branch fails when it steps off the grid, lands on the wrong letter, or reuses a cell.
Mapping the Template to a Grid
| Template step | Word search version |
|---|---|
| Choose | Mark the current cell as visited |
| Explore | Recurse into the four neighbours with `k + 1` |
| Unchoose | Put the original letter back |
| Success | `k == len(word)` |
| Prune | Out of bounds, wrong letter, or already visited |
The visited mark is the state you must restore. You could keep a separate visited set, but overwriting the cell in place with a sentinel such as '#' does the same job with no extra memory. A sentinel is a value that can never match a real letter. The in-place mark also merges the "already visited" check into the letter comparison, since '#' never equals word[k].
The Code
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')) # FalseThe outer any tries every cell as a starting point. The inner any stops at the first neighbour that succeeds. The restore line runs on success and on failure alike, so the board is unchanged when exist returns.
Common Errors
- Forgetting to restore the cell. Later starting points then see
'#'where a letter used to be, and the search misses valid paths. The caller's board also comes back corrupted. - Checking
k == len(word)after the bounds check. If the word ends at the edge of the grid, the final call steps out of bounds and returnsFalsebefore it can report success. Check for success first. - Returning early before the restore. If you write
if backtrack(...): return Trueinside a loop, the marked cell is never restored on the success path. That only works when you don't care about the board afterwards. - Choosing a sentinel that can appear in the word. A sentinel like that makes a visited cell look like a valid match.
Cost
Each cell can start a search. After the first step, each step has at most three new directions, because one neighbour is the cell you came from. For a grid of R × C cells and a word of length L, that gives O(R · C · 3^L) time and O(L) recursion depth. The letter mismatch check prunes most branches early, so real running times are usually far below this bound.
Exercise
The grid is [list('AB'), list('CD')]. Without the visited mark (that is, with the lines that save, overwrite, and restore the cell removed), what does exist(grid, 'ABA') return, and what should it return?
Show answer
Without the mark it returns True, because the path A to B and then back to A reuses the top-left cell. The correct answer is False: the grid contains only one A, and a path cannot use the same cell twice.
Exercise
Why does the code compare k with len(word) before the bounds check, and not after?
Show answer
The call that reaches k == len(word) has already matched every letter, and its coordinates may lie outside the grid because the last match was at an edge. If the bounds check ran first, that call would return False and hide a valid match.