|
| 1 | +// TC: O(K × L + M × N × 4^L) |
| 2 | +// SC: O(K × L + L) |
| 3 | +// K: num of words |
| 4 | +// L: length of the longest word |
| 5 | + |
| 6 | +function findWords(board: string[][], words: string[]): string[] { |
| 7 | + const result: string[] = []; |
| 8 | + const root: TrieNode = buildTrie(words); |
| 9 | + const rows = board.length; |
| 10 | + const cols = board[0].length; |
| 11 | + |
| 12 | + function backtrack(row: number, col: number, node: TrieNode) { |
| 13 | + const char = board[row][col]; |
| 14 | + const nextNode = node[char] as TrieNode; |
| 15 | + |
| 16 | + if (!nextNode) return; |
| 17 | + |
| 18 | + const word = nextNode["$"]; |
| 19 | + if (typeof word === "string") { |
| 20 | + result.push(word); |
| 21 | + delete nextNode["$"]; // avoid duplicate |
| 22 | + } |
| 23 | + |
| 24 | + board[row][col] = ""; // mark as visited |
| 25 | + |
| 26 | + const directions = [ |
| 27 | + [1, 0], |
| 28 | + [-1, 0], |
| 29 | + [0, 1], |
| 30 | + [0, -1], |
| 31 | + ]; |
| 32 | + |
| 33 | + for (const [dx, dy] of directions) { |
| 34 | + const newRow = row + dx; |
| 35 | + const newCol = col + dy; |
| 36 | + |
| 37 | + if ( |
| 38 | + newRow >= 0 && |
| 39 | + newRow < rows && |
| 40 | + newCol >= 0 && |
| 41 | + newCol < cols && |
| 42 | + board[newRow][newCol] !== "$" |
| 43 | + ) { |
| 44 | + backtrack(newRow, newCol, nextNode); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + board[row][col] = char; |
| 49 | + } |
| 50 | + |
| 51 | + for (let r = 0; r < rows; r++) { |
| 52 | + for (let c = 0; c < cols; c++) { |
| 53 | + backtrack(r, c, root); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return result; |
| 58 | +} |
| 59 | + |
| 60 | +// Trie |
| 61 | +// { |
| 62 | +// "e": { |
| 63 | +// "a": { |
| 64 | +// "t": { |
| 65 | +// "#": "eat" |
| 66 | +// } |
| 67 | +// } |
| 68 | +// } |
| 69 | +// } |
| 70 | + |
| 71 | +type TrieNode = { |
| 72 | + [key: string]: TrieNode | string; |
| 73 | +}; |
| 74 | + |
| 75 | +function buildTrie(words: string[]): TrieNode { |
| 76 | + const root: TrieNode = {}; |
| 77 | + for (const word of words) { |
| 78 | + let node = root; |
| 79 | + for (const char of word) { |
| 80 | + if (!node[char]) node[char] = {}; |
| 81 | + node = node[char] as TrieNode; |
| 82 | + } |
| 83 | + node["$"] = word; // end of word |
| 84 | + } |
| 85 | + return root; |
| 86 | +} |
0 commit comments