|
| 1 | +public class Solution { |
| 2 | + /* |
| 3 | + time complexity: O(M × N × 3^L) |
| 4 | + space complexity: O(M × N + L) |
| 5 | + */ |
| 6 | + private int rows, cols; |
| 7 | + private boolean[][] visited; |
| 8 | + private final int[] dx = {0, 1, 0, -1}; |
| 9 | + private final int[] dy = {1, 0, -1, 0}; |
| 10 | + |
| 11 | + public boolean exist(char[][] board, String word) { |
| 12 | + rows = board.length; |
| 13 | + cols = board[0].length; |
| 14 | + visited = new boolean[rows][cols]; |
| 15 | + |
| 16 | + for (int i = 0; i < rows; i++) { |
| 17 | + for (int j = 0; j < cols; j++) { |
| 18 | + if (dfs(board, word, i, j, 0)) { |
| 19 | + return true; |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | + return false; |
| 24 | + } |
| 25 | + |
| 26 | + private boolean dfs(char[][] board, String word, int x, int y, int idx) { |
| 27 | + if (idx == word.length()) return true; |
| 28 | + |
| 29 | + if (x < 0 || y < 0 || x >= rows || y >= cols) return false; |
| 30 | + if (visited[x][y] || board[x][y] != word.charAt(idx)) return false; |
| 31 | + |
| 32 | + visited[x][y] = true; |
| 33 | + |
| 34 | + for (int d = 0; d < 4; d++) { |
| 35 | + if (dfs(board, word, x + dx[d], y + dy[d], idx + 1)) { |
| 36 | + return true; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + visited[x][y] = false; // 백트래킹 |
| 41 | + return false; |
| 42 | + } |
| 43 | +} |
0 commit comments