|
1 | 1 | class Solution {
|
2 |
| - public int[][] dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; |
| 2 | + public static final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; |
| 3 | + |
3 | 4 | public boolean exist(char[][] board, String word) {
|
4 |
| - if (board.length == 0 || board[0].length == 0) { |
5 |
| - return false; |
6 |
| - } |
| 5 | + int rows = board.length; |
| 6 | + int cols = board[0].length; |
7 | 7 | for (int i = 0; i < board.length; i++) {
|
8 | 8 | for (int j = 0; j < board[0].length; j++) {
|
9 |
| - if (exists(board, i, j, word, 0, new boolean[board.length][board[0].length])) { |
| 9 | + if (dfs(board, word, 0, new boolean[rows][cols], i, j)) { |
10 | 10 | return true;
|
11 | 11 | }
|
12 | 12 | }
|
13 | 13 | }
|
14 | 14 | return false;
|
15 |
| - } |
16 |
| - |
17 |
| - private boolean exists(char[][] board, int i, int j, String word, int idx, boolean[][] visited) { |
| 15 | + } |
| 16 | + |
| 17 | + private boolean dfs(char[][] board, String word, int idx, boolean[][] visited, int i, int j) { |
18 | 18 | if (idx == word.length()) {
|
19 | 19 | return true;
|
20 | 20 | }
|
21 |
| - if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] || word.charAt(idx) != board[i][j]) { |
| 21 | + if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] |
| 22 | + || board[i][j] != word.charAt(idx)) { |
22 | 23 | return false;
|
23 | 24 | }
|
24 | 25 | visited[i][j] = true;
|
25 |
| - for (int[] dir : dirs) { |
26 |
| - if (exists(board, i + dir[0], j + dir[1], word, idx + 1, visited)) { |
27 |
| - return true; |
28 |
| - } |
| 26 | + boolean ans = false; |
| 27 | + for (int[] dir : DIRS) { |
| 28 | + ans = ans || dfs(board, word, idx + 1, visited, i + dir[0], j + dir[1]); |
29 | 29 | }
|
30 | 30 | visited[i][j] = false;
|
31 |
| - return false; |
| 31 | + return ans; |
32 | 32 | }
|
33 | 33 | }
|
0 commit comments