Find every dictionary word that can be spelled by an allowed path through a letter board.
Problem
Input. A rectangular board of independent mutable single-character rows and a dictionary list words.
Output. Return each dictionary word that has at least one valid board path, once per distinct word.
Rules. A path moves up, down, left, or right and cannot reuse a coordinate within that path.
Separate candidate paths may share cells. Words must match complete paths, not merely dictionary prefixes.
Exclude # from board and dictionary; the reference ignores empty dictionary strings.
Result order is not required. The board is restored on normal return; empty boards return [].
Example. Rows "oat", "eth", "eat" with words ["oat", "oath", "eat", "pea"] return "oat", "oath", and "eat".
The word "pea" is absent; finding several paths for "eat" would still emit it only once.
Picture
Two states advance together: the current board coordinate and the trie node for the path’s prefix. A missing character edge rejects every dictionary continuation sharing that prefix. Board marks belong only to the active recursive path.
From (0,0), follow o,a,t through (0,1),(1,1).
Pop the terminal value oat, but retain child h to reach oath at (1,2).
After emitting oath, restore h,t,a,o while removing the exhausted trie chain.
Later, (2,0),(2,1),(1,1) spells eat.
No cell contains p, so pea is absent.
Restoring the board permits later coordinate reuse; consuming trie terminals prevents duplicate word output across paths. Pruning is safe only when both terminal and children are gone.
Problem trace
Separate a/ab terminal case: emit once and continue the surviving prefix
Reference drawing
Problem trace
Remove the found terminal without destroying the prefix needed by a longer word
Execution trace
double border complete word
- edges
- [root -> o, root -> e, root -> p, o -> oa, e -> ea, p -> pe, oa -> oat, ea -> eat, pe -> pea, oat -> oath]
- board
- [[o,a,t],[e,t,h],[e,a,t]]
- terminals
- double borders mark oat, oath, eat, and pea
- o
- not shown→(0, 0)
- trie prefix
- not shown→o
- board write
- not shown→(0,0): o -> #
- o
- not shown→(0, 0)
- a
- (0, 0)→(0, 1)
- trie prefix
- o→o-a
- a
- not shown→(0, 1)
- t
- (0, 1)→(1, 1)
- trie prefix
- o-a→o-a-t
- t
- not shown→(1, 1)
- h
- (1, 1)→(1, 2)
- trie prefix
- o-a-t→o-a-t-h
- search cursor
- (1, 2)→(0, 0)
- o
- (0, 0)→not shown
- a
- (0, 1)→not shown
- e
- (0, 0)→(1, 0)
- trie prefix
- not shown→e
- rejected neighbors
- not shown→o, e, t are not child a
- e
- not shown→(2, 0)
- a
- (1, 0)→(2, 1)
- trie prefix
- e→e-a
- a
- not shown→(2, 1)
- t
- (2, 1)→(1, 1)
- trie prefix
- e-a→e-a-t
- search cursor
- (1, 1)→(2, 0)
- e
- (2, 0)→not shown
- a
- (2, 1)→not shown
- Recognize it
- Use a trie when many dictionary words must be searched on the same board and their prefixes can share traversal work.
- Keep true
- At each recursive call, the marked board path contains distinct adjacent cells spelling exactly the trie path to node; every emitted terminal has been removed, and every pruned trie branch can no longer produce an unseen word.
- Reuse it
- When many searches share prefixes, traverse input and trie in lockstep, encode path-local visited state reversibly, remove consumed outputs, and prune nodes only after their subtree is exhausted.
Code
def _make_word_trie(words: list[str]) -> dict:
trie: dict = {}
for word in words:
node = trie
for char in word:
node = node.setdefault(char, {})
node[None] = word
return trie
def _find_words_from(
board: list[list[str]], row: int, col: int, node: dict, answer: list[str]
) -> None:
char = board[row][col]
if char not in node:
return
next_node = node[char]
word = next_node.pop(None, None)
if word:
answer.append(word)
board[row][col] = "#"
for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)):
next_row = row + row_step
next_col = col + col_step
if 0 <= next_row < len(board) and 0 <= next_col < len(board[0]):
_find_words_from(board, next_row, next_col, next_node, answer)
board[row][col] = char
if not next_node:
node.pop(char)
def find_words(board: list[list[str]], words: list[str]) -> list[str]:
trie = _make_word_trie(words)
answer: list[str] = []
for row in range(len(board)):
for col in range(len(board[0])):
_find_words_from(board, row, col, trie, answer)
return answer
The result is discovery order ["oat","oath","eat"], not lexicographic order.
Duplicate dictionary entries share one terminal.
The public call builds a private trie; the helper intentionally consumes the trie it receives.
Normal returns restore the board; exceptions can leave the in-place reference marked.
For total dictionary characters and longest word length , construction takes expected map work. A loose search bound is , with trie and path storage. Prefix pruning helps particular inputs; it does not guarantee polynomial search or remove recursion limits.
Failure Check
Deleting the whole oat node on its first terminal hit loses oath.
Keeping consumed terminals can emit one word repeatedly.
Global board visitation wrongly blocks later starts.
Change to Read-Only Board Search
New task: Forbid board writes and allow any character, including #.
Picture and change: Use path-local coordinate membership, retain trie terminals, and deduplicate output in a set.
def find_words_readonly(board, words):
if not board or not board[0]:
return []
trie, found, used = _make_word_trie(words), set(), set()
def visit(row, column, node):
if (row, column) in used or board[row][column] not in node:
return
following = node[board[row][column]]
word = following.get(None)
if word:
found.add(word)
used.add((row, column))
try:
for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
nr, nc = row + dr, column + dc
if 0 <= nr < len(board) and 0 <= nc < len(board[0]):
visit(nr, nc, following)
finally:
used.remove((row, column))
for row in range(len(board)):
for column in range(len(board[0])):
visit(row, column, trie)
return sorted(found)
Check: Board [["#","a"]] with ["#a","##"] returns ["#a"], with no reuse or writes.
For board aa and words ["a","aa"], return ["a","aa"] despite multiple paths.
Empty words remain excluded.
Sorting adds output-comparison cost; retaining terminals and branches sacrifices the source’s consumed-output pruning.
Use when: Mutation is forbidden or no sentinel character is safe.
Change to Occurrence Counts
New task: Count coordinate-path occurrences for each unique nonempty dictionary word, including absent words with zero.
Picture and change: Keep terminals and branches after each hit; each distinct simple path contributes another count.
def word_path_counts(board, words):
counts = dict.fromkeys(sorted(set(words) - {""}), 0)
if not board or not board[0]:
return counts
trie, used = _make_word_trie(list(counts)), set()
def visit(row, column, node):
if (row, column) in used or board[row][column] not in node:
return
following = node[board[row][column]]
word = following.get(None)
if word is not None:
counts[word] += 1
used.add((row, column))
for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
nr, nc = row + dr, column + dc
if 0 <= nr < len(board) and 0 <= nc < len(board[0]):
visit(nr, nc, following)
used.remove((row, column))
for row in range(len(board)):
for column in range(len(board[0])):
visit(row, column, trie)
return counts
Check: Board aa with ["a","aa","aaa"] returns {"a":2,"aa":2,"aaa":0}.
Opposite traversal directions are separate coordinate paths, not duplicate strings.
This variant cannot prune a word after its first occurrence.
Counting can require exploring every matching path and manipulating growing integer counts.
Use when: Multiplicity, rather than unique dictionary membership, defines the result.
Transfer Check
Why can the original search remove an empty trie branch globally?
Answer
It has no unseen terminal or continuing child for any later start. That proof depends on unique-word output, not occurrence counting.