|
1 | 1 | class Solution {
|
2 |
| - |
3 |
| - private final int[][] DIRS = {{1, 0}, {0, 1}, {0, -1}, {-1, 0}}; |
4 |
| - |
5 |
| - public boolean exist(char[][] board, String word) { |
6 |
| - int m = board.length; |
7 |
| - int n = board[0].length; |
8 |
| - for (int i = 0; i < board.length; i++) { |
9 |
| - for (int j = 0; j < board[0].length; j++) { |
10 |
| - if (found(board, i, j, word, 0, m, n)) { |
11 |
| - return true; |
| 2 | + |
| 3 | + private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; |
| 4 | + |
| 5 | + public boolean exist(char[][] board, String word) { |
| 6 | + int m = board.length; |
| 7 | + int n = board[0].length; |
| 8 | + for (int i = 0; i < m; i++) { |
| 9 | + for (int j = 0; j < n; j++) { |
| 10 | + if (isFound(board, word, 0, i, j, m, n)) { |
| 11 | + return true; |
| 12 | + } |
| 13 | + } |
12 | 14 | }
|
13 |
| - } |
| 15 | + return false; |
14 | 16 | }
|
15 |
| - return false; |
16 |
| - } |
17 |
| - |
18 |
| - private boolean found(char[][] board, int x, int y, String word, int idx, int m, int n) { |
19 |
| - if (idx == word.length()) { |
20 |
| - return true; |
21 |
| - } |
22 |
| - if (x < 0 || x == m || y < 0 || y == n || board[x][y] != word.charAt(idx)) { |
23 |
| - return false; |
24 |
| - } |
25 |
| - board[x][y] = '#'; |
26 |
| - for (int[] dir : DIRS) { |
27 |
| - if (found(board, x + dir[0], y + dir[1], word, idx + 1, m, n)) { |
28 |
| - return true; |
29 |
| - } |
| 17 | + |
| 18 | + private boolean isFound(char[][] board, String word, int idx, int row, int col, int m, int n) { |
| 19 | + if (idx == word.length()) { |
| 20 | + return true; |
| 21 | + } |
| 22 | + if (row < 0 || col < 0 || row >= m || col >= n || board[row][col] != word.charAt(idx)) { |
| 23 | + return false; |
| 24 | + } |
| 25 | + board[row][col] ^= 256; |
| 26 | + boolean result = false; |
| 27 | + for (int[] dir : DIRS) { |
| 28 | + result = result || isFound(board, word, idx + 1, row + dir[0], col + dir[1], m, n); |
| 29 | + } |
| 30 | + board[row][col] ^= 256; |
| 31 | + return result; |
30 | 32 | }
|
31 |
| - board[x][y] = word.charAt(idx); |
32 |
| - return false; |
33 |
| - } |
34 | 33 | }
|
0 commit comments