|
| 1 | +/* |
| 2 | +# Time Complexity: O(w + m * n * 4^10) |
| 3 | + - trie에 word 하나(최대 길이 10)를 삽입하는 데에는 O(10) = O(1) 이므로, trie 전체를 생성하는 데에는 O(w) (w는 words의 length) |
| 4 | + - dfs 탐색을 하면서, 모든 경로를 탐색 (최대 depth는 10) |
| 5 | +# Space Complexity: O(w) |
| 6 | + - trie를 생성하면, 최대 10글자 * w개 문자열 = O(10w) = O(w) |
| 7 | +*/ |
| 8 | +class Solution { |
| 9 | + |
| 10 | + private class Trie { |
| 11 | + char val; |
| 12 | + boolean ends; |
| 13 | + Map<Character, Trie> children; |
| 14 | + |
| 15 | + Trie(char val) { |
| 16 | + this.val = val; |
| 17 | + this.children = new HashMap<>(); |
| 18 | + } |
| 19 | + } |
| 20 | + public List<String> findWords(char[][] board, String[] words) { |
| 21 | + // Trie 생성 및 세팅 |
| 22 | + Trie root = new Trie('.'); |
| 23 | + for (String word : words) { |
| 24 | + Trie curr = root; |
| 25 | + for (int i = 0; i < word.length(); i++) { |
| 26 | + char ch = word.charAt(i); |
| 27 | + curr.children.putIfAbsent(ch, new Trie(ch)); |
| 28 | + curr = curr.children.get(ch); |
| 29 | + } |
| 30 | + curr.ends = true; |
| 31 | + } |
| 32 | + |
| 33 | + // trie와 dfs를 사용하여, 단어가 존재하는지 확인 |
| 34 | + int m = board.length; |
| 35 | + int n = board[0].length; |
| 36 | + boolean[][] visited = new boolean[m][n]; |
| 37 | + StringBuilder sb = new StringBuilder(); |
| 38 | + Set<String> ans = new HashSet<>(); |
| 39 | + for (int i = 0; i < m; i++) { |
| 40 | + for (int j = 0; j < n; j++) { |
| 41 | + if (!root.children.containsKey(board[i][j])) continue; |
| 42 | + |
| 43 | + visited[i][j] = true; |
| 44 | + sb.append(board[i][j]); |
| 45 | + dfs(m, n, board, visited, i, j, root.children.get(board[i][j]), sb, ans); // |
| 46 | + sb.deleteCharAt(0); |
| 47 | + visited[i][j] = false; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + return ans.stream().collect(Collectors.toList()); |
| 52 | + } |
| 53 | + |
| 54 | + private void dfs(int m, int n, char[][] board, boolean[][] visited, int r, int c, Trie curr, StringBuilder sb, Set<String> ans) { |
| 55 | + if (curr.ends) ans.add(sb.toString()); |
| 56 | + |
| 57 | + int[] dr = {-1, 0, 1, 0}; |
| 58 | + int[] dc = {0, 1, 0, -1}; |
| 59 | + |
| 60 | + for (int i = 0; i < 4; i++) { |
| 61 | + int nr = r + dr[i]; |
| 62 | + int nc = c + dc[i]; |
| 63 | + if (nr < 0 || nr >= m || nc < 0 || nc >= n || visited[nr][nc]) continue; |
| 64 | + if (!curr.children.containsKey(board[nr][nc])) continue; |
| 65 | + |
| 66 | + visited[nr][nc] = true; |
| 67 | + sb.append(board[nr][nc]); |
| 68 | + dfs(m, n, board, visited, nr, nc, curr.children.get(board[nr][nc]), sb, ans); |
| 69 | + sb.deleteCharAt(sb.length() - 1); |
| 70 | + visited[nr][nc] = false; |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments