public class Solution {
public int[][] dir={{-1,0},{1,0},{0,1},{0,-1}};
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
boolean vis[]=new boolean[matrix.length];
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
vis[i*cols+j]=true;
if(find(i,j,0,matrix,rows,cols,str,vis)){
return true;
}
vis[i*cols+j]=false;
}
}
return false;
}
public boolean find(int x,int y,int id,char[] matrix,int rows,int cols,char[] str,boolean vis[]){
int pos=x*cols+y;
if(matrix[pos]!=str[id]) return false;
if(id==str.length-1) return true;
for(int i=0;i<4;i++){
int tx=x+dir[i][0];
int ty=y+dir[i][1];
if(tx<0||tx>=rows||ty<0||ty>=cols) continue;
int tp=tx*cols+ty;
if(vis[tp]) continue;
vis[tp]=true;
boolean flag=find(tx,ty,id+1,matrix,rows,cols,str,vis);
vis[tp]=false;
if(flag) return true;
}
return false;
}
}
矩阵中的路径(dfs)
最新推荐文章于 2022-02-21 21:40:10 发布