79 Word Search

1. Question

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.
For example, Givenboard=
1
[
2
['A','B','C','E'],
3
['S','F','C','S'],
4
['A','D','E','E']
5
]
Copied!
word ="ABCCED", -> returnstrue,
word ="SEE", -> returntrue,
word ="ABCB", -> returnsfalse.

2. Implementation

(1) Backtracking
1
class Solution {
2
public boolean exist(char[][] board, String word) {
3
if (board == null || board.length == 0 || word == null || word.length() == 0) {
4
return false;
5
}
6
7
int m = board.length, n = board[0].length;
8
boolean[][] visited = new boolean[m][n];
9
10
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
11
12
for (int i = 0; i < m; i++) {
13
for (int j = 0; j < n; j++) {
14
if (searchWord(0, i, j, word, directions, visited, board)) {
15
return true;
16
}
17
}
18
}
19
return false;
20
}
21
22
public boolean searchWord(int index, int row, int col, String word, int[][] directions, boolean[][] visited, char[][] board) {
23
if (index == word.length()) {
24
return true;
25
}
26
27
if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || board[row][col] != word.charAt(index) || visited[row][col]) {
28
return false;
29
}
30
31
visited[row][col] = true;
32
for (int[] direction : directions) {
33
int nextRow = row + direction[0];
34
int nextCol = col + direction[1];
35
36
if (searchWord(index + 1, nextRow, nextCol, word, directions, visited, board)) {
37
return true;
38
}
39
}
40
visited[row][col] = false;
41
return false;
42
}
43
}
Copied!

3. Time & Space Complexity

时间复杂度O(mn*4^L),m为board的行数,n为board的列数,L为word的长度, 空间复杂度O(mn)