79. Word Search

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
class Solution {
private static final int[][] DIRECTIONS = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

public boolean exist(char[][] board, String word) {
int m = board.length, n = board[0].length;

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (dfs(board, i, j, word, 0)) {
return true;
}
}
}

return false;
}

private boolean dfs(char[][] board, int i, int j, String word, int index) {
int m = board.length, n = board[0].length;

// 注意终止条件,此处是为了处理二维网格只有一个字符的场景,board: [["a"]], word: "a"
// 如果 index 到达 word.length() 才返回 true 则单个字符时无法返回 true
if (index == word.length() - 1) {
if (board[i][j] == word.charAt(index)) {
return true;
} else {
return false;
}
}

if (board[i][j] == word.charAt(index)) {
char c = board[i][j];
board[i][j] = '*';
for (int[] direction : DIRECTIONS) {
int nextI = i + direction[0], nextJ = j + direction[1];
if (nextI >= 0 && nextI < m && nextJ >= 0 && nextJ < n) {
if (dfs(board, nextI, nextJ, word, index + 1)) {
return true;
}
}
}
board[i][j] = c;
}

return false;
}
}

以上解法在能够搜索到单词的情况下修改了原二维网格,如果原二维网格不能修改则需要做另行处理。

References

79. Word Search
剑指 Offer 12. 矩阵中的路径