|
3 | 3 | public class _79 {
|
4 | 4 |
|
5 | 5 | public static class Solution1 {
|
6 |
| - |
7 |
| - public boolean exist(char[][] board, String word) { |
8 |
| - int m = board.length; |
9 |
| - int n = board[0].length; |
10 |
| - boolean[][] visited = new boolean[m][n]; |
11 |
| - for (int i = 0; i < m; i++) { |
12 |
| - for (int j = 0; j < n; j++) { |
13 |
| - if (dfs(board, visited, i, j, word, 0)) { |
14 |
| - return true; |
15 |
| - } |
16 |
| - } |
17 |
| - } |
18 |
| - return false; |
19 |
| - } |
20 |
| - |
21 |
| - final int[] dirs = new int[]{0, 1, 0, -1, 0}; |
22 |
| - |
23 |
| - boolean dfs(char[][] board, boolean[][] visited, int row, int col, String word, int index) { |
24 |
| - if (index >= word.length() || word.charAt(index) != board[row][col]) { |
25 |
| - return false; |
26 |
| - } else if (index == word.length() - 1 && word.charAt(index) == board[row][col]) { |
27 |
| - visited[row][col] = true; |
28 |
| - return true; |
29 |
| - } |
30 |
| - visited[row][col] = true;//set it to true for this case |
31 |
| - boolean result = false; |
32 |
| - for (int i = 0; i < 4; i++) { |
33 |
| - int nextRow = row + dirs[i]; |
34 |
| - int nextCol = col + dirs[i + 1]; |
35 |
| - if (nextRow < 0 || nextRow >= board.length || nextCol < 0 || nextCol >= board[0].length || visited[nextRow][nextCol]) { |
36 |
| - continue; |
37 |
| - } |
38 |
| - result = dfs(board, visited, nextRow, nextCol, word, index + 1); |
39 |
| - if (result) { |
40 |
| - return result; |
41 |
| - } else { |
42 |
| - visited[nextRow][nextCol] = false;//set it back to false if this road doesn't work to allow it for other paths, this is backtracking!!! |
43 |
| - } |
44 |
| - } |
45 |
| - return result; |
46 |
| - } |
47 |
| - } |
48 |
| - |
49 |
| - public static class Solution2 { |
50 | 6 | //credit: https://discuss.leetcode.com/topic/21142/my-java-solution
|
51 | 7 |
|
52 | 8 | boolean[][] visited;
|
|
0 commit comments