Subject description:
Please design a function that determines whether there is a route that contains all the characters of a character string in a matrix. A lattice path may start from any of the matrix, each step in the matrix can be left, right, up, down one grid. If one path through the matrix of one grid, the following can not enter the grid again.
Such abcesfcsadee e.g. 3 X 4
matrix containing the path "bcced" in a string, but does not contain the matrix "abcb" path, since the first character string occupies the first row of the matrix b in the second lattice after that, the path can not enter the grid again.
Analysis of ideas:
Backtracking to solve, from a point on the matrix, if the value of this point is equal to the first value in the string, then the next we can continue the search from upper left lower right node of the point. But it can not be repeated traversal, if eventually find a path string it returns true, if you can not return false.
Code:
public class Solution {
public boolean hasPath(char []matrix,int rows,int cols,char[]str){
if(matrix==null||str==null)
return false;
boolean []flag=new boolean[matrix.length]; //标记是否被访问过
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(findPath(matrix,rows,cols,i,j,str,0,flag))
return true;
}
}
return false;
}
public boolean findPath(char []matrix,int rows,int cols,int i,int j,char[]str,int k,boolean[]flag){
int index=i*cols+j;
if(i<0||i>=rows||j<0||j>=cols||flag[index]||matrix[index]!=str[k])
return false;
if(k==str.length-1)
return true; //证明找到了该条路径
flag[index]=true; //当前点被访问过了
if(findPath(matrix,rows,cols,i,j-1,str,k+1,flag) //向左搜
||findPath(matrix,rows,cols,i-1,j,str,k+1,flag)//向上搜
||findPath(matrix,rows,cols,i,j+1,str,k+1,flag)//向右搜
||findPath(matrix,rows,cols,i+1,j,str,k+1,flag)//向下搜
)
return true;
flag[index]=false; //回溯
return false;
}
}