-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain79.java
More file actions
36 lines (34 loc) · 1.09 KB
/
Main79.java
File metadata and controls
36 lines (34 loc) · 1.09 KB
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
31
32
33
34
35
36
package HOT100;
public class Main79 {
public boolean exist(char[][] board, String word) {
int n = board.length;
int m = board[0].length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(board[i][j] == word.charAt(0)) {
if(dfs(board, word, i, j, 0)){
return true;
}
}
}
}
return false;
}
private boolean dfs(char[][] board, String word, int i, int j, int index) {
if(index == word.length()) {
return true;
}
if(i < 0 || j < 0 || i >= board.length || j >= board[0].length) {
return false;
}
if(board[i][j] != word.charAt(index)) {
return false;
}
char c = board[i][j];
board[i][j] = '\0';
boolean res = dfs(board, word, i + 1, j, index + 1) || dfs(board, word, i - 1, j, index + 1)
|| dfs(board, word, i, j + 1, index + 1) || dfs(board, word, i, j - 1, index + 1);
board[i][j] = c;
return res;
}
}