题目意思:给定一维字符数组,判断在这个字符数组构成的矩阵中是否可以找到另一个字符串路径
算法思想:1、题目说,路径中走过的格子不能重复,因此,需要一个mark数组来标记该格子是否走过
2、排除一些特殊情况,当矩阵数组或字符数组为空或null是,返回false
3、遍历矩阵数组,找到矩阵中字符与字符数组第一个字符相同的位置,然后从该位置进行左右上下的遍历
【遍历过程中,如果越界或者格子已经被走过了,或者不相等,则返回false;否则,进行四个方向的递归,如果递归退出,则说明这个位置不对,将这个位置置为false;直到字符数组走到最后,则说明前面的字符都匹配成功了,则返回true】
4、循环遍历结束,没有找到相同的,则返回false
代码如下:
public static boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
if (matrix.length==0 || str.length==0 || str==null){
return false;
}
int strindex=0;
boolean[] mark=new boolean[matrix.length];
for (int i=0;i<rows;i++){
for (int j=0;j<cols;j++){
if (canBePath(matrix,rows,cols,i,j,str,strindex,mark)){
return true;
}
}
}
return false;
}
private static boolean canBePath(char[] matrix, int rows, int cols, int i, int j, char[] str, int strindex, boolean[] mark) {
int mindex=i*cols+j;
if (i<0 || j<0 || i>=rows || j>=cols || matrix[mindex]!=str[strindex] || mark[mindex]==true){
return false;
}
if (strindex==str.length-1){
return true;
}
mark[mindex]=true;
if (canBePath(matrix,rows,cols,i-1,j,str,strindex+1,mark)
||canBePath(matrix,rows,cols,i+1,j,str,strindex+1,mark)
||canBePath(matrix,rows,cols,i,j-1,str,strindex+1,mark)
||canBePath(matrix,rows,cols,i,j+1,str,strindex+1,mark)){
return true;
}
mark[mindex]=false;
return false;
}