|
| 1 | +/* |
| 2 | +n : 셀 수 |
| 3 | +L : 단어 길이 |
| 4 | +Time Complexity : O(n * 4^L) |
| 5 | +Space Complexity : O(L) |
| 6 | +*/ |
| 7 | + |
| 8 | +class Solution { |
| 9 | + public boolean exist(char[][] board, String word) { |
| 10 | + if (board == null || board.length == 0 || board[0].length == 0) return false; |
| 11 | + int rows = board.length; |
| 12 | + int cols = board[0].length; |
| 13 | + boolean[][] visited = new boolean[rows][cols]; |
| 14 | + |
| 15 | + for (int i = 0; i < rows; i++) { |
| 16 | + for (int j = 0; j < cols; j++) { |
| 17 | + if (backtrack(board, word, i, j, 0, visited)) { |
| 18 | + return true; |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + return false; |
| 23 | + } |
| 24 | + |
| 25 | + private boolean backtrack(char[][] board, String word, int row, int col, int index, boolean[][] visited) { |
| 26 | + if (index == word.length()) return true; |
| 27 | + if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || visited[row][col] || board[row][col] != word.charAt(index)) { |
| 28 | + return false; |
| 29 | + } |
| 30 | + visited[row][col] = true; |
| 31 | + |
| 32 | + int[] dx = {-1, 1, 0, 0}; |
| 33 | + int[] dy = {0, 0, -1, 1}; |
| 34 | + |
| 35 | + for (int i = 0; i < 4; i++) { |
| 36 | + int newRow = row + dx[i]; |
| 37 | + int newCol = col + dy[i]; |
| 38 | + |
| 39 | + if (backtrack(board, word, newRow, newCol, index + 1, visited)) { |
| 40 | + visited[row][col] = false; |
| 41 | + return true; |
| 42 | + } |
| 43 | + } |
| 44 | + visited[row][col] = false; |
| 45 | + return false; |
| 46 | + } |
| 47 | +} |
0 commit comments