
思路:dfs思想,找到与word第一个字母相同的位置开始bfs,用id记录当前位置,如果id==word.length-1则返回true
注意:dfs的不同访问顺序可能导致结果不同,所以在每次遍历一条路径失败后,需要把相应的vis[i][j]恢复为未访问状态
code:
class Solution {
public int[][] dir={
{
0,1},{
0,-1},{
1,0},{
-1,0}};
public int rows;
public int cols;
public String word;
public boolean ans=false;
public boolean exist(char[][] board, String word) {
rows=board.length;
cols=board[0].length;
this.word=word;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(word.charAt(0)==board[i][j]){
boolean vis[][]=new boolean[rows][cols];
bfs(board,vis,i,j,0);
}
}
}
return ans;
}
public void bfs(char[][] board,boolean vis[][],int i,int j,int id){
vis[i][j]=true;
if(id==word.length()-1){
ans=true;
return;
}
for(int k=0;k<4;k++){
int newi=i+dir[k][0];
int newj=j+dir[k][1];
if(0<=newi&&newi<rows&&0<=newj&&newj<cols
&&!vis[newi][newj]&&board[newi][newj]==word.charAt(id+1)){
bfs(board,vis,newi,newj,id+1);
vis[newi][newj]=false;
}
}
}
}
原文链接: https://blog.csdn.net/qq_53568730/article/details/136842883