Given an m×n board of letters and a list of words, return every word that can be formed from sequentially adjacent (horizontal or vertical) cells, using each cell at most once per word.
Put all words in a trie and run one DFS from every cell, walking the board and the trie together. A path stops as soon as no word has it as a prefix; reaching a stored word records it once.
1function findWords(board: string[][], words: string[]): string[] {2const root: Trie = { kids: new Map(), word: null };3for (const w of words) {4let n = root;5for (const c of w) n = n.kids.get(c) ?? n.kids.set(c, { kids: new Map(), word: null }).get(c)!;6n.word = w;7}8const res: string[] = [], m = board.length, n = board[0].length;9const dfs = (r: number, c: number, node: Trie) => {10const ch = board[r]?.[c], next = ch && node.kids.get(ch);11if (!next) return;12if (next.word) { res.push(next.word); next.word = null; }13board[r][c] = "#";14dfs(r + 1, c, next); dfs(r - 1, c, next); dfs(r, c + 1, next); dfs(r, c - 1, next);15board[r][c] = ch;16};17for (let r = 0; r < m; r++) for (let c = 0; c < n; c++) dfs(r, c, root);18return res;19}
| o | a | a | n |
| e | t | a | e |
| i | h | k | r |
| i | f | l | v |
Insert 4 words into a trie.
Space: play/pause · ←/→: step