Word Search

Word Search

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.

Solution1

DFS

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
public boolean exist(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
boolean[][] visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (dfs(board, visited, i, j, word, 0)) {
return true;
}
}
}
return false;
}

public boolean dfs(char[][] board, boolean[][] visited, int x, int y, String word, int k) {
if (k == word.length()) {
return true;
}
if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) {
return false;
}
if (visited[x][y]) {
return false;
}
if (board[x][y] != word.charAt(k)) {
return false;
}

visited[x][y] = true;
if (dfs(board, visited, x - 1, y, word, k + 1)) {
return true;
}
if (dfs(board, visited, x + 1, y, word, k + 1)) {
return true;
}
if (dfs(board, visited, x, y - 1, word, k + 1)) {
return true;
}
if (dfs(board, visited, x, y + 1, word, k + 1)) {
return true;
}
visited[x][y] = false;
return false;
}