Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example
Given board =

1
2
3
4
5
[
"ABCE",
"SFCS",
"ADEE"
]

word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.


DFS

有个点需要注意一下,当找到之后,就要停止DFS,所以要检查flag

以下代码是自己写的,也可以参考九章: http://www.jiuzhang.com/solutions/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
public class Solution {
boolean flag = false;
int[] dx = {0, 0, 1, -1};
int[] dy = {1, -1, 0, 0};
public boolean exist(char[][] board, String word) {
boolean[][] visited = new boolean[board.length][board[0].length];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (flag)
return flag;
if (board[i][j] == word.charAt(0)) {
visited[i][j] = true;
dfs(board, visited, i, j, word, 1);
visited[i][j] = false;
}
}
}
return flag;
}
//around (i, j) to find word[idx]
public void dfs(char[][] board, boolean[][] visited, int x, int y, String word, int idx) {
if (flag || idx == word.length()) {
flag = true;
return;
}
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < board.length && ny >= 0 && ny < board[0].length && visited[nx][ny] == false && board[nx][ny] == word.charAt(idx)) {
visited[nx][ny] = true;
dfs(board, visited, nx, ny, word, idx + 1);
visited[nx][ny] = false;
}
}
}
}