|
| 1 | +class Solution { |
| 2 | + int m, n; |
| 3 | + int[] dx = new int[]{0, 1, 0, -1}; |
| 4 | + int[] dy = new int[]{1, 0, -1, 0}; |
| 5 | + boolean answer = false; |
| 6 | + boolean[][] visit; |
| 7 | + |
| 8 | + public boolean exist(char[][] board, String word) { |
| 9 | + m = board.length; |
| 10 | + n = board[0].length; |
| 11 | + visit = new boolean[m][n]; |
| 12 | + |
| 13 | + for (int i = 0; i < m; i++){ |
| 14 | + for (int j = 0; j < n; j++){ |
| 15 | + if (board[i][j] == word.charAt(0)){ |
| 16 | + visit[i][j] = true; |
| 17 | + dfs(i, j, board, word, 0); |
| 18 | + visit[i][j] = false; |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + return answer; |
| 23 | + } |
| 24 | + |
| 25 | + public void dfs(int cx, int cy, char[][] board, String word, int depth){ |
| 26 | + if (depth == word.length()-1){ |
| 27 | + answer = true; |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + for (int i = 0; i < 4; i++){ |
| 32 | + int nx = cx + dx[i]; |
| 33 | + int ny = cy + dy[i]; |
| 34 | + int nextDepth = depth + 1; |
| 35 | + |
| 36 | + if (outOfRange(nx, ny)||visit[nx][ny]) continue; |
| 37 | + if (board[nx][ny] == word.charAt(nextDepth)){ |
| 38 | + visit[nx][ny] = true; |
| 39 | + dfs(nx, ny, board, word, nextDepth); |
| 40 | + visit[nx][ny] = false; |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + public boolean outOfRange(int x, int y){ |
| 46 | + return (x < 0 || x >= m) || (y < 0 || y >= n); |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | + |
0 commit comments