题目描述
AC代码
public class Solution {
char[] matrix;
char[] str;
public boolean hasPath(char[] _matrix, int rows, int cols, char[] _str)
{
matrix=_matrix;
str=_str;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(dfs(rows,cols,0,i,j))
return true;
}
}
return false;
}
boolean dfs(int rows,int cols,int u,int x,int y){
int pos=x*cols+y;
if(matrix[pos]!=str[u])
return false;
if(u==(str.length-1))
return true;
char tmp=matrix[pos];
matrix[pos]='*';
int dx[]={-1,0,1,0},dy[]={0,1,0,-1};
for(int i=0;i<4;i++){
int a=x+dx[i],b=y+dy[i];
if(a>=0&&a<rows&&b>=0&&b<cols)
if(dfs(rows,cols,u+1,a,b))
return true;
}
matrix[pos]=tmp;
return false;
}
}