CodeArchon

hardTriesMicrosoftAmazonGoogle

Puzzle Board Harvest

A word-search generator sweeps a letter grid and collects every dictionary word spelled by connected neighboring cells.

Given an m×n board of characters and a list of words, return all words on the board. A word can be formed by sequentially adjacent cells (no reuse within the same word).

Choose approach

o
a
a
n
e
t
a
e
i
h
k
r
i
f
l
v
1/13
Narrationstep 1 of 13

Build trie from 4 words; sweep board with DFS pruning via trie.

1def findWords(board, words):
2 root = {}
3 for w in words:
4 n = root
5 for c in w: n = n.setdefault(c, {})
6 n['$'] = w
7 R, C, out = len(board), len(board[0]), []
8 def dfs(r, c, n):
9 ch = board[r][c]
10 if ch == '#' or ch not in n: return
11 nxt = n[ch]
12 if '$' in nxt:
13 out.append(nxt['$']); del nxt['$']
14 board[r][c] = '#'
15 for dr, dc in [(-1,0),(1,0),(0,-1),(0,1)]:
16 nr, nc = r+dr, c+dc
17 if 0 <= nr < R and 0 <= nc < C: dfs(nr, nc, nxt)
18 board[r][c] = ch
19 for r in range(R):
20 for c in range(C): dfs(r, c, root)
21 return out
Variables
rows=4
cols=4
words=oath, pea, eat, rain

How to think about it

  1. A separate DFS per word is wasteful — the trie fuses prefixes.
  2. Prune the moment the current letter has no trie branch.
  3. Clear `$word` sentinel on collection to avoid duplicates.

Edge cases to catch in interview

  • No words -> empty output.
  • Word longer than any grid path -> never collected.

Examples

Example 1[]
{"grid":[["a","b"],["c","d"]],"words":["abcb"]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed