|
| 1 | +class Solution { |
| 2 | + |
| 3 | + // 시간 복잡도: O(m * n * 4^L) - m: 행, n: 열, L: 단어 길이 |
| 4 | + // 공간 복잡도: O(m * n) - 방문 체크를 위한 공간 |
| 5 | + public boolean exist(char[][] board, String word) { |
| 6 | + int rows = board.length; |
| 7 | + int cols = board[0].length; |
| 8 | + |
| 9 | + for (int r = 0; r < rows; r++) { |
| 10 | + for (int c = 0; c < cols; c++) { |
| 11 | + if (dfs(board, word, 0, r, c)) { |
| 12 | + return true; |
| 13 | + } |
| 14 | + } |
| 15 | + } |
| 16 | + |
| 17 | + return false; |
| 18 | + } |
| 19 | + |
| 20 | + private boolean dfs(char[][] board, String word, int index, int r, int c) { |
| 21 | + if (index == word.length()) { |
| 22 | + return true; |
| 23 | + } |
| 24 | + |
| 25 | + if (r < 0 || r >= board.length || c < 0 || c >= board[0].length || board[r][c] != word.charAt( |
| 26 | + index)) { |
| 27 | + return false; |
| 28 | + } |
| 29 | + |
| 30 | + char temp = board[r][c]; |
| 31 | + board[r][c] = '#'; |
| 32 | + |
| 33 | + boolean found = |
| 34 | + dfs(board, word, index + 1, r + 1, c) || |
| 35 | + dfs(board, word, index + 1, r - 1, c) || |
| 36 | + dfs(board, word, index + 1, r, c + 1) || |
| 37 | + dfs(board, word, index + 1, r, c - 1); |
| 38 | + |
| 39 | + board[r][c] = temp; |
| 40 | + return found; |
| 41 | + } |
| 42 | +} |
| 43 | + |
0 commit comments