-
Notifications
You must be signed in to change notification settings - Fork 0
/
79. 单词搜索.java
60 lines (58 loc) · 2.06 KB
/
79. 单词搜索.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
int[][] map;
public boolean exist(char[][] board, String word) {
map = new int[board.length][board[0].length];
char[] wordChar = word.toCharArray();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == wordChar[0]) {
map[i][j] = 1;
if (dfs(board, i, j, wordChar, 1)) {
return true;
}
map[i][j] = 0;
}
}
}
return false;
}
private boolean dfs(char[][] board, int i, int j, char[] wordChar, int index) {
if (index < wordChar.length) {
if (i + 1 < board.length && map[i + 1][j] == 0 && board[i + 1][j] == wordChar[index]) {
map[i + 1][j] = 1;
if (dfs(board, i + 1, j, wordChar, index + 1)) {
return true;
} else {
map[i + 1][j] = 0;
}
}
if (i - 1 >= 0 && map[i - 1][j] == 0 && board[i - 1][j] == wordChar[index]) {
map[i - 1][j] = 1;
if (dfs(board, i - 1, j, wordChar, index + 1)) {
return true;
} else {
map[i - 1][j] = 0;
}
}
if (j + 1 < board[0].length && map[i][j + 1] == 0 && board[i][j + 1] == wordChar[index]) {
map[i][j + 1] = 1;
if (dfs(board, i, j + 1, wordChar, index + 1)) {
return true;
} else {
map[i][j + 1] = 0;
}
}
if (j - 1 >= 0 && map[i][j - 1] == 0 && board[i][j - 1] == wordChar[index]) {
map[i][j - 1] = 1;
if (dfs(board, i, j - 1, wordChar, index + 1)) {
return true;
} else {
map[i][j - 1] = 0;
}
}
return false;
} else {
return true;
}
}
}