|
| 1 | +/* |
| 2 | +L : 평균 단어 길이 |
| 3 | +Time Complexity: O(M * N * 4^L) |
| 4 | +Space Complexity: O(∑L + M × N) |
| 5 | +*/ |
| 6 | +class TrieNode { |
| 7 | + children: Map<string, TrieNode> |
| 8 | + word: string | null |
| 9 | + |
| 10 | + constructor() { |
| 11 | + this.children = new Map() |
| 12 | + this.word = null |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +class Trie { |
| 17 | + root: TrieNode |
| 18 | + constructor() { |
| 19 | + this.root = new TrieNode() |
| 20 | + } |
| 21 | + |
| 22 | + insert(word: string): void { |
| 23 | + let node = this.root |
| 24 | + |
| 25 | + for (const char of word) { |
| 26 | + if (!node.children.has(char)) { |
| 27 | + node.children.set(char, new TrieNode()) |
| 28 | + } |
| 29 | + node = node.children.get(char) |
| 30 | + } |
| 31 | + node.word = word |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +function dfs(board: string[][], row: number, col: number, node: TrieNode, visited: boolean[][], result: string[]): void { |
| 36 | + const rows = board.length |
| 37 | + const cols = board[0].length |
| 38 | + if (row < 0 || row >= board.length || |
| 39 | + col < 0 || col >= board[0].length || |
| 40 | + visited[row][col]) { |
| 41 | + return |
| 42 | + } |
| 43 | + const char = board[row][col] |
| 44 | + if (!node.children.has(char)) { |
| 45 | + return |
| 46 | + } |
| 47 | + node = node.children.get(char)! |
| 48 | + |
| 49 | + if (node.word !== null) { |
| 50 | + result.push(node.word) |
| 51 | + node.word = null |
| 52 | + } |
| 53 | + const originalChar = board[row][col] |
| 54 | + visited[row][col] = true |
| 55 | + const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]] |
| 56 | + for (const [dr, dc] of directions) { |
| 57 | + dfs(board, row + dr, col + dc, node, visited, result) |
| 58 | + } |
| 59 | + visited[row][col] = false |
| 60 | + } |
| 61 | + |
| 62 | +function findWords(board: string[][], words: string[]): string[] { |
| 63 | + if (!board || board.length === 0 || !board[0] || board[0].length === 0) { |
| 64 | + return [] |
| 65 | + } |
| 66 | + const result: string[] = [] |
| 67 | + const trie = new Trie() |
| 68 | + |
| 69 | + for (const word of words) { |
| 70 | + trie.insert(word) |
| 71 | + } |
| 72 | + |
| 73 | + const rows = board.length |
| 74 | + const cols = board[0].length |
| 75 | + const visited = Array(rows).fill(null).map(() => Array(cols).fill(false)) |
| 76 | + |
| 77 | + for (let i = 0; i < rows; i++) { |
| 78 | + for (let j = 0; j < cols; j++) { |
| 79 | + dfs(board, i, j, trie.root, visited, result) |
| 80 | + } |
| 81 | + } |
| 82 | + return result |
| 83 | +}; |
0 commit comments