05. Word Search II (Board Search with Trie)
Given an $m \times n$ board of characters and a list of strings words, return all words on the board.
How It Works & Algorithmic Design
Solves using Prefix Trie Tree + Grid Backtracking DFS:
- Build Prefix Trie: Insert all
wordsinto Trie. Store completewordreference at terminal leaf nodes. - Grid Traversal DFS
dfs(r, c, trieNode):- Base Case: if cell out of bounds or
board[r][c] === '#'or character not intrieNode.children, return. - Matching Child: step into
childNode. - Word Discovered: if
childNode.word !== null, push to result and setchildNode.word = null(prevents duplicates). - Mark visited
board[r][c] = '#'and recurse 4 directions. - Restore cell
board[r][c] = originalChar.
- Base Case: if cell out of bounds or
Why This Approach Works Best
Trie prefix matching prunes search paths across thousands of words simultaneously in $O(M \cdot N \cdot 4^L)$ worst-case.
Example Walkthrough
[["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Grid and word dictionary.
"oath", "eat"
Valid board word paths.
["oath", "eat"]
Discovered words.
Answer: Word Search II Trie implementation
function findWords(board, words) {
const root = {};
for (const w of words) {
let node = root;
for (const c of w) {
if (!node[c]) node[c] = {};
node = node[c];
}
node.word = w;
}
const res = [];
const m = board.length, n = board[0].length;
function dfs(r, c, node) {
const ch = board[r][c];
if (!node[ch]) return;
node = node[ch];
if (node.word) {
res.push(node.word);
node.word = null;
}
board[r][c] = '#';
const dirs = [[1,0],[-1,0],[0,1],[0,-1]];
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < m && nc < n && board[nr][nc] !== '#') {
dfs(nr, nc, node);
}
}
board[r][c] = ch;
}
for (let r = 0; r < m; r++) {
for (let c = 0; c < n; c++) {
dfs(r, c, root);
}
}
return res;
}Build Prefix Trie and perform 4-directional grid DFS backtracking to find matching words.
Store complete
wordstring directly inside Trie leaf node.Set
node.word = nullwhen found to avoid duplicate results.Trie prefix checks prune invalid board branches fast.