|
| 1 | +// ๋ชจ๋ ์์น์์ DFS๋ฅผ ์คํ or BFS๋ฅผ ๋๋ฉด์ ๋จ์ด ์ฐพ๋ ๊ฒฝ์ฐ ๋ชจ๋ ๊ฒฝ์ฐ์ ํ์์์์ด ๋ฐ์ |
| 2 | +// ๋์ ํ ํด๊ฒฐ์ ๋ชปํ ๊ฑฐ ๊ฐ์์ GPT์ ๋์์ ๋ฐ์ |
| 3 | +// Trie๋ฅผ ์ด์ฉํ๋๋ฐ ์กฐ๊ธ ๋ ๊ณ ๋ฏผํด๋ด์ผํ ๋ฏ |
| 4 | +class TrieNode { |
| 5 | + Map<Character, TrieNode> children = new HashMap<>(); |
| 6 | + String word = null; |
| 7 | +} |
| 8 | + |
| 9 | +class Solution { |
| 10 | + public List<String> findWords(char[][] board, String[] words) { |
| 11 | + List<String> result = new ArrayList<>(); |
| 12 | + TrieNode root = buildTrie(words); |
| 13 | + |
| 14 | + for (int i = 0; i < board.length; i++) { |
| 15 | + for (int j = 0; j < board[0].length; j++) { |
| 16 | + dfs(board, i, j, root, result); |
| 17 | + } |
| 18 | + } |
| 19 | + return result; |
| 20 | + } |
| 21 | + |
| 22 | + // Trie(ํธ๋ผ์ด) ์๋ฃ๊ตฌ์กฐ๋ฅผ ๊ตฌ์ถ |
| 23 | + private TrieNode buildTrie(String[] words) { |
| 24 | + TrieNode root = new TrieNode(); |
| 25 | + for (String word : words) { |
| 26 | + TrieNode node = root; |
| 27 | + for (char c : word.toCharArray()) { |
| 28 | + node.children.putIfAbsent(c, new TrieNode()); |
| 29 | + node = node.children.get(c); |
| 30 | + } |
| 31 | + node.word = word; |
| 32 | + } |
| 33 | + return root; |
| 34 | + } |
| 35 | + |
| 36 | + // DFS + ๋ฐฑํธ๋ํน ํ์ |
| 37 | + private void dfs(char[][] board, int i, int j, TrieNode node, List<String> result) { |
| 38 | + char c = board[i][j]; |
| 39 | + if (!node.children.containsKey(c)) return; // ํ์ฌ ๋ฌธ์์ ์ผ์นํ๋ ๊ฒ์ด Trie์ ์์ผ๋ฉด ์ข
๋ฃ |
| 40 | + |
| 41 | + TrieNode nextNode = node.children.get(c); |
| 42 | + if (nextNode.word != null) { // ๋จ์ด๋ฅผ ์ฐพ์์ผ๋ฉด ๊ฒฐ๊ณผ ๋ฆฌ์คํธ์ ์ถ๊ฐ |
| 43 | + result.add(nextNode.word); |
| 44 | + nextNode.word = null; // ์ค๋ณต ๋ฐฉ์ง๋ฅผ ์ํด ์ ๊ฑฐ |
| 45 | + } |
| 46 | + |
| 47 | + // ๋ฐฉ๋ฌธ ํ์ (๋ฐฑํธ๋ํน์ ์ํด) |
| 48 | + board[i][j] = '#'; |
| 49 | + |
| 50 | + // 4๋ฐฉํฅ ํ์ |
| 51 | + int[] dx = {-1, 1, 0, 0}; |
| 52 | + int[] dy = {0, 0, -1, 1}; |
| 53 | + for (int d = 0; d < 4; d++) { |
| 54 | + int x = i + dx[d], y = j + dy[d]; |
| 55 | + if (x >= 0 && x < board.length && y >= 0 && y < board[0].length) { |
| 56 | + dfs(board, x, y, nextNode, result); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + // ๋ฐฑํธ๋ํน (์๋ ๋ฌธ์๋ก ๋ณต์) |
| 61 | + board[i][j] = c; |
| 62 | + |
| 63 | + // **์ต์ ํ**: ๋ ์ด์ ์์์ด ์์ผ๋ฉด Trie์์ ํด๋น ๋
ธ๋ ์ญ์ |
| 64 | + if (nextNode.children.isEmpty()) { |
| 65 | + node.children.remove(c); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments