[LeetCode] Problem 79 - 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.

Example

1
2
3
4
5
6
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.

Code

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
public boolean exist(char[][] board, String word) {
int n = board.length;
int m = board[0].length;
boolean[][] visited = new boolean[n][m];

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

return false;
}

private boolean search(char[][] board, boolean[][] visited, String word, int idx, int x, int y, int n, int m) {
if (idx == word.length())
return true;

if (x < 0 || x >= n || y < 0 || y >= m || visited[x][y] || board[x][y] != word.charAt(idx))
return false;

visited[x][y] = true;

boolean exist = search(board, visited, word, idx + 1, x + 1, y, n, m) ||
search(board, visited, word, idx + 1, x - 1, y, n, m) ||
search(board, visited, word, idx + 1, x, y + 1, n, m) ||
search(board, visited, word, idx + 1, x, y - 1, n, m);

visited[x][y] = false;
return exist;
}