|
| 1 | +class SolutionWordSearch { |
| 2 | + |
| 3 | + int[] dx = new int[]{0, 0, -1, 1}; |
| 4 | + int[] dy = new int[]{-1, 1, 0, 0}; |
| 5 | + |
| 6 | + public boolean exist(char[][] board, String word) { |
| 7 | + // 상하좌우 방문 여부 체크하면서 DFS 탐색 |
| 8 | + // index 기준으로 word와 비교하면서 같을 때만 추가 탐색 |
| 9 | + // 시간복잡도: O(N) > 방문 여부 체크하면서 기방문한 곳은 탐색하지 않기 때문 |
| 10 | + // 공간복잡도: O(1) > 별도 메모리 할당하지 않음 |
| 11 | + for (int i = 0; i < board.length; i++) { |
| 12 | + for (int j = 0; j < board[0].length; j++) { |
| 13 | + if (dfs(board, i, j, word, 0)) { |
| 14 | + return true; |
| 15 | + } |
| 16 | + } |
| 17 | + } |
| 18 | + return false; |
| 19 | + } |
| 20 | + |
| 21 | + public boolean dfs(char[][] board, int x, int y, String word, int index) { |
| 22 | + if (index >= word.length()) { |
| 23 | + return true; |
| 24 | + } |
| 25 | + // board 밖이면 return false |
| 26 | + if (x >= board.length || y >= board[0].length || x < 0 || y < 0) { |
| 27 | + return false; |
| 28 | + } |
| 29 | + // 이미 방문했거나 정답 조건에 맞지 않으면 return false |
| 30 | + if (board[x][y] != word.charAt(index)) { |
| 31 | + return false; |
| 32 | + } |
| 33 | + |
| 34 | + // 현재 위치의 문자를 임시로 변경하여 방문 처리 |
| 35 | + char temp = board[x][y]; |
| 36 | + board[x][y] = '#'; |
| 37 | + |
| 38 | + index++; |
| 39 | + for (int i = 0; i < 4; i++) { |
| 40 | + if (dfs(board, x + dx[i], y + dy[i], word, index)) { |
| 41 | + return true; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + // 방문 처리를 되돌림 |
| 46 | + board[x][y] = temp; |
| 47 | + |
| 48 | + return false; |
| 49 | + } |
| 50 | +} |
0 commit comments