|
| 1 | +/** |
| 2 | + * [Problem]: [212] Word Search II |
| 3 | + * (https://leetcode.com/problems/word-search-ii/) |
| 4 | + */ |
| 5 | + |
| 6 | +class TrieNode { |
| 7 | + children: Map<string, TrieNode> = new Map(); |
| 8 | + word: string | null = null; |
| 9 | +} |
| 10 | + |
| 11 | +//시간복잡도 O(m * n * 4^s) |
| 12 | +//공간복잡도 O(trie 저장 공간(word * length) + result) |
| 13 | +function findWords(board: string[][], words: string[]): string[] { |
| 14 | + const result: string[] = []; |
| 15 | + const rows = board.length; |
| 16 | + const cols = board[0].length; |
| 17 | + |
| 18 | + const root = new TrieNode(); |
| 19 | + for (const word of words) { |
| 20 | + let node = root; |
| 21 | + |
| 22 | + for (const char of word) { |
| 23 | + if (!node.children.has(char)) { |
| 24 | + node.children.set(char, new TrieNode()); |
| 25 | + } |
| 26 | + node = node.children.get(char)!; |
| 27 | + } |
| 28 | + |
| 29 | + node.word = word; |
| 30 | + } |
| 31 | + |
| 32 | + const dfs = (i: number, j: number, node: TrieNode) => { |
| 33 | + const char = board[i][j]; |
| 34 | + const next = node.children.get(char); |
| 35 | + if (!next) return; |
| 36 | + |
| 37 | + if (next.word) { |
| 38 | + result.push(next.word); |
| 39 | + next.word = null; |
| 40 | + } |
| 41 | + |
| 42 | + board[i][j] = "#"; |
| 43 | + |
| 44 | + const directions = [ |
| 45 | + [0, 1], |
| 46 | + [1, 0], |
| 47 | + [0, -1], |
| 48 | + [-1, 0], |
| 49 | + ]; |
| 50 | + |
| 51 | + for (const [dx, dy] of directions) { |
| 52 | + const ni = i + dx; |
| 53 | + const nj = j + dy; |
| 54 | + |
| 55 | + if (ni >= 0 && ni < rows && nj >= 0 && nj < cols && board[ni][nj] !== "#") { |
| 56 | + dfs(ni, nj, next); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + board[i][j] = char; |
| 61 | + |
| 62 | + if (next.children.size === 0) { |
| 63 | + node.children.delete(char); |
| 64 | + } |
| 65 | + }; |
| 66 | + |
| 67 | + for (let i = 0; i < rows; i++) { |
| 68 | + for (let j = 0; j < cols; j++) { |
| 69 | + dfs(i, j, root); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + return result; |
| 74 | +} |
0 commit comments