-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
30 lines (28 loc) · 1.06 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
private boolean[][] visited;
public boolean exist(char[][] board, String word) {
int m = board.length, n = board[0].length;
visited = new boolean[m][n];
char[] chars = word.toCharArray();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
boolean res = dfs(board, i, j, chars, 0);
if (res) return true;
}
}
return false;
}
private boolean dfs(char[][] board, int i, int j, char[] chars, int cur) {
if (cur == chars.length) return true;
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return false;
if (visited[i][j] || board[i][j] != chars[cur]) return false;
visited[i][j] = true;
int next = cur + 1;
boolean res = dfs(board, i + 1, j, chars, next)
|| dfs(board, i - 1, j, chars, next)
|| dfs(board, i, j + 1, chars, next)
|| dfs(board, i, j - 1, chars, next);
visited[i][j] = false;
return res;
}
}