leetcode 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.

For example,
Given board =

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

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


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
class  {
public boolean exist(char[][] board, String word) {
if(board == null || board.length == 0) return false;
int m = board.length;
int n = board[0].length;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(search(board, word, i, j, 0)){
return true;
}
}
}
return false;
}
public boolean search(char[][] board, String word, int i, int j, int pos){
if(i<0 || j < 0 || i >= board.length || j >= board[0].length)
return false;
if(board[i][j] != word.charAt(pos)) return false;
if(board[i][j] == word.charAt(pos) && pos == word.length()-1)
return true;
board[i][j] = ' ';
boolean result =
search(board, word, i-1, j, pos+1) ||
search(board, word, i+1, j, pos + 1) ||
search(board, word, i, j-1, pos + 1) ||
search(board, word, i, j+1, pos + 1);
board[i][j] = word.charAt(pos);
return result;
}
}
  • 运用递归的思想,判断第i行第j列的字符是否等于当前判断字符,若等于,则判断(i,j)周围四个点是否等于下一个字符,依次递归,知道最后一个字符若相等,返回true,否则若i,j超过board返回或者不相等,返回False;