题目:
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 =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word =
"ABCB"
, -> returns
false
.
解法:
题目要求在一个二维表中查找单词,按邻居顺序排列即可。
这里很容易想到利用深度优先遍历的思想,找到一个元素与word[i]匹配后,按上下左右的顺序检查它的邻居是否与word[i+1]匹配。当i>=word.length时,即宣告查找成功。
需要注意的是每个元素只能访问一遍,因此可以用一个visit二维数组来存储对应元素是否被访问过,也可以用一个变量保存当前访问的元素,然后将其置为‘。’,表示它已被访问,在DFS结束后恢复现场。
这题对时间卡的非常紧,所以尽量避免一些不太需要的比较,才能AC。
public class No79_WordSearch {
public static void main(String[] args){
System.out.println(exist(new char[][]{{'B'},{'A'},{'B'}}, "BABA"));
}
public static boolean exist(char[][] board, String word) {
int m = board.length;
if(m == 0) return false;
int n = board[0].length;
if(n == 0) return false;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(match(board, word, 0, i, j)) return true;
}
}
return false;
}
public static boolean match(char[][] board, String word, int index, int i, int j){
if(index >= word.length()) return true;
if(i<0 || i>=board.length || j<0 || j>=board[0].length) return false;
if(word.charAt(index) != board[i][j]) return false;
if(board[i][j] == '.') return false;
char tmp = board[i][j];
board[i][j] = '.';
boolean top = false, bottom = false, left = false, right = false;
if(i>=1)
top = match(board, word, index+1, i-1, j);
if(!top)
bottom = match(board, word, index+1, i+1, j);
if(!top && !bottom)
left = match(board, word, index+1, i, j-1);
if(!top && !bottom && !left)
right = match(board, word, index+1, i, j+1);
board[i][j] = tmp;
return top||bottom||left||right;
}
}