Sub topic 10
Backtracking on Grids: Word Search
So far the choices in this tutorial have been "take or skip this element" or "put this unused value next." On a grid, a choice means stepping to a neighboring cell. The template stays the same. What changes is the state you have to undo: which cells the current path has already used.
This chapter assumes you are comfortable with the choose-explore-unchoose template, with copying versus mutating shared state, and with two-dimensional lists in Python indexed as board[r][c].
The Problem
You are given a grid of letters and a word. Decide whether the word can be traced through the grid by moving up, down, left, or right, one letter per step, without using any cell twice in the same path.
grid = [list('ABCE'),
list('SFCS'),
list('ADEE')]ABCCED is present. It starts at the top-left A, goes right twice, down, down, then left. ABCB is absent: the only B sits next to the C you just came from, so reaching it again would reuse a cell.
Modeling the Search as a State-Space Tree
A partial solution is a path of cells that spells a prefix of the word. You can describe it with three numbers:
(r, c): the cell you are about to try.k: the index of the letter inwordthat this cell must match.
The root of the tree is not a single node. Every cell on the board is a possible starting point, so you get one tree per cell, and the outer loop tries each one in turn. Inside a tree, each node has at most four children (the neighbors). Beyond the first step it has at most three, because the cell you came from is already used.
Most of the tree is pruned at depth one. A neighbor whose letter does not match word[k] is rejected before anything is marked, which is why word search runs far faster in practice than its worst-case bound suggests.
The Reference Implementation
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 function maps onto the template like this:
| Template step | Line(s) in `backtrack` |
|---|---|
| Success base case | `if k == len(word): return True` |
| Reject invalid state | bounds check and `board[r][c] != word[k]` |
| Choose | `board[r][c] = '#'` |
| Explore | `any(backtrack(...) for each direction)` |
| Unchoose | `board[r][c] = saved` |
The order of the two base cases matters. The success check comes first because k == len(word) means the previous cell matched the last letter. At that point (r, c) may be off the board, and that is fine, because you are not going to read that cell.
Why the Sentinel Doubles as the Visited Check
Writing '#' into the cell does two jobs. It records that the path uses this cell, and the existing mismatch test board[r][c] != word[k] rejects the cell automatically if the path tries to return to it. You need no separate visited structure and no extra condition. Because the check reads only the cell's current value, it costs O(1) time and no extra memory.
`any` Short-Circuits, and Restoration Still Runs
any stops at the first True, so once one direction succeeds, the remaining directions are never explored. The restore line comes after the any call rather than inside it, so it runs whether or not the search succeeded. The board is identical before and after exist returns. That property matters as soon as you reuse the board.
A Common Bug: Returning Before Restoring
A natural rewrite uses an explicit loop with an early return:
def exist_buggy(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] = '#'
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
if backtrack(r + dr, c + dc, k + 1):
return True # BUG: board[r][c] is never restored
board[r][c] = saved
return False
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_buggy(grid, 'ABCCED')) # True
print(exist_buggy(grid, 'SEE')) # False, but the correct answer is True
print(grid) # every cell on the ABCCED path is still '#'The first answer is correct, so a test that asks a single question will pass. The second call runs on a corrupted board and gives the wrong answer. This bug shows up whenever you check several words against one board, which is exactly the "find all words from a dictionary" variant. The fix is to restore before every exit:
def exist_fixed(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] = '#'
try:
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
if backtrack(r + dr, c + dc, k + 1):
return True
return False
finally:
board[r][c] = saved # runs on every exit path
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_fixed(grid, 'ABCCED')) # True
print(exist_fixed(grid, 'SEE')) # Truetry/finally guarantees that the undo step runs no matter how the function exits, including when it raises an exception.
Other Mistakes to Watch For
| Mistake | Symptom | Fix |
|---|---|---|
| Marking the cell before checking that it matches | Cells get marked and never unmarked when the function returns on a mismatch | Check bounds and the letter first, then mark |
| Checking bounds after indexing | `IndexError`, or silent wraparound because Python accepts `board[-1]` | Put the bounds tests before `board[r][c]` in the `or` chain |
| One shared `visited` set that is never cleared between start cells | Later starting points fail wrongly | Remove each cell on unchoose so the set is empty when a start finishes |
| Allowing diagonal moves without being asked to | Finds words that should not be present | Use exactly the four orthogonal offsets |
| Checking `k == len(word) - 1` after the move instead of before | Off-by-one errors on one-letter words | Use the `k == len(word)` base case shown above |
Cost of the Search
Let the board be R × C and the word have length L. Each starting cell spawns a tree. Its first step has up to 4 branches and each later step has at most 3, so one start explores O(4 · 3^(L−1)) nodes. The worst case overall is O(R · C · 3^L) time. The recursion depth is at most L + 1, so the extra space is O(L) beyond the board itself, because the board stores the visited marks.
The worst case is real. A board full of A with the word AAAA…AB explores almost every path before it fails. Python's default recursion limit of about 1000 frames also caps the word length the recursive version can handle.
Cheap Pruning Before You Search
Two checks done before the search remove many hopeless cases:
from collections import Counter
def exist_pruned(board, word):
if not word:
return True
rows, cols = len(board), len(board[0])
if len(word) > rows * cols:
return False
have = Counter(ch for row in board for ch in row)
need = Counter(word)
if any(have[ch] < n for ch, n in need.items()):
return False # the board lacks some letter often enough
if have[word[0]] > have[word[-1]]:
word = word[::-1] # start from the rarer end: fewer roots
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] = None # None never equals a letter of the 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))
big = [['A'] * 6 for _ in range(6)]
print(exist_pruned(big, 'A' * 12 + 'B')) # False, instantly
print(exist_pruned([list('ABCE'), list('SFCS'), list('ADEE')], 'SEE')) # TrueReversing the word is safe because a path read backwards spells the reversed word. With 'A' * 12 + 'B', the count check alone rejects the case that would otherwise take exponential time.
Exercises
Exercise
Why does the reference exist not need a separate check to stop the path from stepping back onto the cell it just came from?
Show answer
The cell it came from holds the sentinel '#', which never equals word[k]. The ordinary letter-mismatch test therefore rejects it, along with every other cell already on the current path.
Exercise
Change exist so that it returns the list of (row, col) coordinates of one matching path, or None if there is none. Where do you append and pop?
Show answer
Keep a path list. Append (r, c) right after marking the cell and pop it right before restoring the cell. At k == len(word), return a copy with list(path). In the direction loop, return the first result that is not None. The pop and restore must still run on every exit, so put them in a finally block or restore before each return.
Exercise
The board is 3 x 4 and the word has length 6. Give the worst-case upper bound on the number of backtrack calls that pass the bounds-and-letter check, using the analysis in this chapter.
Show answer
There are 12 starting cells. Each explores at most 4 3^4 = 324 paths, so the bound is 12 324 = 3888. In practice, letter mismatches cut this to a few dozen.