|
| 1 | +/** |
| 2 | + * 문제 설명 |
| 3 | + * - 2차원 배열에서 주어진 단어들을 찾는 문제 |
| 4 | + * |
| 5 | + * 아이디어 |
| 6 | + * 1) Trie 자료구조 + DFS & Backtracking (👀어려웠음..다시 풀어보기) |
| 7 | + * - 주어진 단어들을 Trie 자료구조로 변환 |
| 8 | + * - 2차원 배열을 순회하면서 Trie 자료구조를 사용하여 단어를 찾음 |
| 9 | + * - 찾은 단어는 배열에 추가 |
| 10 | + */ |
| 11 | +class TrieNode { |
| 12 | + private nodes = new Map<string, TrieNode>(); |
| 13 | + word: string | null = null; |
| 14 | + |
| 15 | + add(word: string) { |
| 16 | + let currentNode = this as TrieNode; |
| 17 | + for (const char of word) { |
| 18 | + if (!currentNode.nodes.has(char)) { |
| 19 | + currentNode.nodes.set(char, new TrieNode()); |
| 20 | + } |
| 21 | + currentNode = currentNode.nodes.get(char)!; |
| 22 | + } |
| 23 | + currentNode.word = word; |
| 24 | + } |
| 25 | + |
| 26 | + getNode(char: string) { |
| 27 | + return this.nodes.get(char); |
| 28 | + } |
| 29 | + |
| 30 | + hasChar(char: string) { |
| 31 | + return this.nodes.has(char); |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +function search( |
| 36 | + m: number, |
| 37 | + n: number, |
| 38 | + board: string[][], |
| 39 | + node: TrieNode, |
| 40 | + result: string[] |
| 41 | +) { |
| 42 | + const M = board.length; |
| 43 | + const N = board[0].length; |
| 44 | + if (m < 0 || m >= M || n < 0 || n >= N) return; |
| 45 | + |
| 46 | + const currentChar = board[m][n]; |
| 47 | + if (currentChar === "#" || !node.hasChar(currentChar)) return; |
| 48 | + |
| 49 | + node = node.getNode(currentChar)!; |
| 50 | + |
| 51 | + if (node.word) { |
| 52 | + result.push(node.word); |
| 53 | + node.word = null; |
| 54 | + } |
| 55 | + |
| 56 | + board[m][n] = "#"; |
| 57 | + |
| 58 | + search(m + 1, n, board, node, result); |
| 59 | + search(m - 1, n, board, node, result); |
| 60 | + search(m, n + 1, board, node, result); |
| 61 | + search(m, n - 1, board, node, result); |
| 62 | + |
| 63 | + board[m][n] = currentChar; |
| 64 | +} |
| 65 | + |
| 66 | +function findWords(board: string[][], words: string[]): string[] { |
| 67 | + const root = new TrieNode(); |
| 68 | + for (const word of words) { |
| 69 | + root.add(word); |
| 70 | + } |
| 71 | + |
| 72 | + const result: string[] = []; |
| 73 | + const M = board.length; |
| 74 | + const N = board[0].length; |
| 75 | + |
| 76 | + for (let i = 0; i < M; i++) { |
| 77 | + for (let j = 0; j < N; j++) { |
| 78 | + search(i, j, board, root, result); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + return result; |
| 83 | +} |
0 commit comments