Determine whether a word can be spelled along a nonrepeating orthogonal path through a letter board.
Problem
Input. A rectangular board of independent mutable single-character rows and a string word.
Output. Return True if some allowed path spells the complete word; otherwise return False.
Rules. Consecutive characters must use up, down, left, or right neighbors, never diagonal neighbors.
A path cannot reuse a coordinate; different candidates may reuse cells.
Exclude # from board and word. The reference restores the board on normal return.
An empty word succeeds even on an empty board; a nonempty word fails on an empty board.
Example. Rows "ABCE", "SFCS", "ADEE" contain a path spelling "ABCCED", so return True.
The same board returns False for "ABCB" because the only candidate would need to reuse its B cell.
Picture
At search(row, col, index), marked ancestors spell word[:index].
The candidate must be in bounds, unused and equal to the next character.
Save its character, mark it, then try down, up, right and left.
The trace follows (0,0),(0,1),(0,2),(1,2),(2,2),(2,1).
At E, down is outside, up is already marked and right contains the wrong character.
Left reaches D and completes the word.
Completion is checked before reading another cell; no additional valid neighbor is required.
The Boolean result short-circuits remaining directions, but each accepted call still restores its own cell.
Restoration unwinds D,E,C,C,B,A.
Path ownership is temporary, unlike the permanent component marking used for island counting.
Problem trace
Separate two-cell ABA request: the third visit reuses an already-owned cell
Reference drawing
Problem trace
A cell is unavailable only within the current search path
Execution trace
- start A
- (0, 0)
- word
- ABCCED
- call
- search(0, 0, 0)
- matched prefix
- not shown→A
- call stack
- not shown→A@(0,0),i=0
- attempted
- not shown→down -> (1,0)
- A
- not shown→(0, 0)
- B
- (0, 0)→(0, 1)
- matched prefix
- A→A -> B
- B
- not shown→(0, 1)
- C
- (0, 1)→(0, 2)
- matched prefix
- A -> B→A -> B -> C
- C
- not shown→(0, 2)
- C
- (0, 2)→(1, 2)
- matched prefix
- A -> B -> C→A -> B -> C -> C
- C
- not shown→(1, 2)
- E
- (1, 2)→(2, 2)
- matched prefix
- A -> B -> C -> C→A -> B -> C -> C -> E
- rejected
- not shown→down out of bounds; up # != D; right E != D
- next
- not shown→try left -> (2,1)
- attempted
- down -> (2,2)→not shown
- E
- not shown→(2, 2)
- D
- (2, 2)→(2, 1)
- matched prefix
- A -> B -> C -> C -> E→A -> B -> C -> C -> E -> D
- 6
- not shown→(2, 1)
- D
- (2, 1)→not shown
- restored order
- not shown→D, E, C, C, B, A
- Recognize it
- A word must be assembled as one neighboring-cell path, choices branch in four directions, and a cell may be used once per candidate path but may be reused by later candidates.
- Keep true
- At search(row, col, index), every # cell is exactly one character of the current prefix word[0:index]. Before returning, the call restores its own cell, so sibling branches and later starts see the original board.
- Reuse it
- For path-constrained search, choose one option, mark only the state owned by that choice, recurse, then undo before returning. The same choose-explore-unchoose discipline applies to mazes, permutations, and constraint search.
Code
def word_search(board: list[list[str]], word: str) -> bool:
if not word:
return True
if not board or not board[0]:
return False
def search(row: int, col: int, index: int) -> bool:
if index == len(word):
return True
if not (0 <= row < len(board) and 0 <= col < len(board[0])):
return False
if board[row][col] != word[index]:
return False
char = board[row][col]
board[row][col] = "#"
found = (
search(row + 1, col, index + 1)
or search(row - 1, col, index + 1)
or search(row, col + 1, index + 1)
or search(row, col - 1, index + 1)
)
board[row][col] = char
return found
return any(
search(row, col, 0)
for row in range(len(board))
for col in range(len(board[0]))
)
For word length , a loose upper bound is time and path stack space. The search is exponential, not linear merely because each current path avoids repeats. Long words can exceed Python’s recursion limit. Normal returns restore the board; an exception can leave this in-place reference marked.
Failure Check
On board AB, ABA must fail because the first A cannot be reused.
A permanent visited set also incorrectly blocks coordinates needed by later candidates.
Returning immediately on success before restoring would change the caller’s board.
Change to an Arbitrary Alphabet
New task: Allow # in the board or query.
Picture and change: Track used coordinates in a path-local set instead of overwriting characters.
The finally block releases ownership even when a recursive call raises.
def word_search_set(board, word):
if not word:
return True
if not board or not board[0]:
return False
used = set()
def search(row, col, index):
if index == len(word):
return True
if not (0 <= row < len(board) and 0 <= col < len(board[0])) or (row, col) in used or board[row][col] != word[index]:
return False
used.add((row, col))
try:
return any(search(row + row_step, col + col_step, index + 1) for row_step, col_step in ((1,0),(-1,0),(0,1),(0,-1)))
finally:
used.remove((row, col))
return any(search(row, col, 0) for row in range(len(board)) for col in range(len(board[0])))
Check: Board [["A","B"]] and "AB#" return False; board [["#","A"]] and "#A" return True.
The first case fools the sentinel reference into accepting a previously used cell as a literal #.
This version never modifies the board.
Use when: No character can be reserved as a marker.
Change to Counting Coordinate Paths
New task: Count every matching simple coordinate path, including opposite traversal orders.
Picture and change: Sum branches instead of stopping at one, and emit one count at the final matched cell.
def count_word_paths(board, word):
if not word:
return 1
if not board or not board[0]:
return 0
used = set()
def search(row, col, index):
if not (0 <= row < len(board) and 0 <= col < len(board[0])) or (row, col) in used or board[row][col] != word[index]:
return 0
if index == len(word) - 1:
return 1
used.add((row, col))
total = sum(search(row + row_step, col + col_step, index + 1) for row_step, col_step in ((1,0),(-1,0),(0,1),(0,-1)))
used.remove((row, col))
return total
return sum(search(row, col, 0) for row in range(len(board)) for col in range(len(board[0])))
Check: A two-by-two board of A has eight directed paths spelling AA: four starts, each with two neighbors.
The empty word contributes one empty path, including on an empty board.
Counting retains exponential worst-case search and current-path storage, not storage for all returned witnesses.
Use when: Distinct coordinate paths, rather than distinct strings, define the output.
Transfer Check
Why not sum the original four recursive calls after reaching the final character?
Answer
All four would report the same completed path, multiplying its contribution by four. Emit once at the final matched cell instead.