参考博客:https://blog.csdn.net/happyaaaaaaaaaaa/article/details/50834335
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:
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.
题目的意思:一开始我以为只是单纯地在grid中找到能表示该单词的字母集合即可,这样主要遍历一下grid来统计一下各单词出现次数与word进行比较即可。后来才发现,是要求能找出一条路径包含word,有则true,无则false。
这样看着就像一道dfs了,为了简化过程我们可以使用一个数组来标记该位置是否已经被访问,并且适当地进行剪枝:数组越界、该点已被访问、当前字母不匹配。
class Solution {
public boolean exist(char[][] board, String word) {
boolean[][] isVisited=new boolean[board.length][board[0].length];//标志该位置是否已进行访问
for(int i=0;i<board.length;i++){
for(int j=0;j<board[i].length;j++){
if(IsExist(board,word,i,j,isVisited,0)){
return true;
}
}
}
return false;
}
private boolean IsExist(char[][] board, String word,int row,int col,boolean[][] isVisited,int index){
int[] trow={0,1,0,-1};//行,右下左上
int[] tcol={1,0,-1,0};//列,右下左上
//先针对数组越界、已经被访问、当前字符不匹配进行剪枝
if(row<0 || row>=board.length || col <0 || col>=board[0].length || isVisited[row][col] == true || board[row][col] != word.charAt(index)){
return false;
}
//遍历结束,index等于word的长度返回true
if(++index == word.length()){//要是index++会溢出
return true;
}
isVisited[row][col]=true;
for(int i=0;i<4;i++){//以board[row][col]为起点,向它的四周进行匹配
if(IsExist(board,word,row+trow[i],col+tcol[i],isVisited,index)){
return true;
}
}
isVisited[row][col]=false;//遍历过后,该点未找到匹配的路径,将该点还原为未访问过
return false;
}
}