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
|
import java.util.ArrayList;
import java.util.List;
class Solution {
static boolean flag = false;
static boolean[][] isFlag;
public boolean exist(char[][] board, String word) {
flag = false; // 每次调用要重置
isFlag = new boolean[board.length][board[0].length];
List<Character> list = new ArrayList<>();
for (int i = 0; i < word.length(); i++) {
list.add(word.charAt(i));
}
// 从每一个点开始尝试匹配
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
dfs(i, j, board, list, 0); // 第0个字符开始匹配
if (flag) return true;
}
}
return false;
}
public static void dfs(int i, int j, char[][] board, List<Character> list, int index) {
// 如果已经全部匹配完了
if (index == list.size()) {
flag = true;
return;
}
// 越界 + 已访问 + 当前字符不匹配
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length ||
isFlag[i][j] || board[i][j] != list.get(index)) {
return;
}
isFlag[i][j] = true;
// 递归向四个方向搜索
dfs(i + 1, j, board, list, index + 1);
dfs(i - 1, j, board, list, index + 1);
dfs(i, j + 1, board, list, index + 1);
dfs(i, j - 1, board, list, index + 1);
isFlag[i][j] = false; // 回溯
}
}
|