|
| 1 | +/** |
| 2 | + * https://leetcode.com/problems/word-search-ii |
| 3 | + * T.C. O(W * L + M * N * 4^L) W: number of words, L: mean length of words, M: rows, N: cols |
| 4 | + * S.C. O(W * L) |
| 5 | + */ |
| 6 | +function findWords(board: string[][], words: string[]): string[] { |
| 7 | + const root = new TrieNode(); |
| 8 | + for (const word of words) { |
| 9 | + let node = root; |
| 10 | + for (const char of word) { |
| 11 | + if (!node.children[char]) { |
| 12 | + node.children[char] = new TrieNode(); |
| 13 | + } |
| 14 | + node = node.children[char]; |
| 15 | + } |
| 16 | + node.word = word; |
| 17 | + node.isEnd = true; |
| 18 | + } |
| 19 | + |
| 20 | + const result = new Set<string>(); |
| 21 | + const rows = board.length; |
| 22 | + const cols = board[0].length; |
| 23 | + |
| 24 | + function dfs(row: number, col: number, node: TrieNode): void { |
| 25 | + if (row < 0 || row >= rows) return; |
| 26 | + if (col < 0 || col >= cols) return; |
| 27 | + if (!board[row][col]) return; |
| 28 | + if (!node.children[board[row][col]]) return; |
| 29 | + |
| 30 | + const char = board[row][col]; |
| 31 | + const currNode = node.children[char]; |
| 32 | + |
| 33 | + if (currNode.isEnd) { |
| 34 | + result.add(currNode.word); |
| 35 | + } |
| 36 | + |
| 37 | + board[row][col] = '#'; |
| 38 | + |
| 39 | + dfs(row + 1, col, currNode); |
| 40 | + dfs(row - 1, col, currNode); |
| 41 | + dfs(row, col + 1, currNode); |
| 42 | + dfs(row, col - 1, currNode); |
| 43 | + |
| 44 | + board[row][col] = char; |
| 45 | + } |
| 46 | + |
| 47 | + for (let i = 0; i < rows; i++) { |
| 48 | + for (let j = 0; j < cols; j++) { |
| 49 | + dfs(i, j, root); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return Array.from(result); |
| 54 | +} |
| 55 | + |
| 56 | +class TrieNode { |
| 57 | + constructor( |
| 58 | + public children: Record<string, TrieNode> = {}, |
| 59 | + public word: string = '', |
| 60 | + public isEnd: boolean = false |
| 61 | + ) {} |
| 62 | +} |
0 commit comments