Poison

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[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

public boolean exist(char[][] board, String word) {
// 注意每个点都能作为搜索起点
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; 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;

if (index == word.length()) {
return true;
}

if (board[i][j] != word.charAt(index)) {
return false;
}

if (index == word.length() - 1) {
// 处理二维网格只有一个字符的场景,board: [["a"]], word: "a"
return true;
}

char c = board[i][j];
board[i][j] = ' ';

for (int[] direction : DIRECTIONS) {
int x = i + direction[0];
int y = j + direction[1];
if (x >= 0 && x < m && y >= 0 && y < n && dfs(board, x, y, word, index + 1)) {
return true;
}
}

board[i][j] = c;
return false;
}
}

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

Reference

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