题目
思路
利用回溯法
回溯算法概念:在许多递归问题当中,我们采取的方法都是穷尽所有的可能,从而找出合法的解。但是在某些情况下,当递归到某一层的时候,根据设置的判断条件,可以 judge 此解是不合法的。在这种情况下,我们就没必要再进行深层次的递归,从而可以提高算法效率。这一类算法我们称为“回溯法”,设置的判断条件称为“剪枝函数”
用一个状态数组保存之前访问过的字符,然后再分别按上,下,左,右递归
代码
public class Solution {
boolean[] flags = null;
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
flags = new boolean[matrix.length];
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(getPath(matrix,rows,cols,str,i,j,0)){
return true;
}
}
}
return false;
}
public boolean getPath(char[] matrix, int rows, int cols, char[] str,int row,int col,int len){
int currentNum=row*cols+col;
if(flags[currentNum] == true || str[len]!= matrix[currentNum])return false;
if(len==(str.length-1)) return true;//到这里,说明最后一个字符串也找到了,直接返回true
flags[currentNum] = true;//设置走过标志
if(row>0 && getPath(matrix,rows,cols,str,row-1,col,len+1))return true;//上
if(row+1<rows && getPath(matrix,rows,cols,str,row+1,col,len+1))return true;//下
if(col>0 && getPath(matrix,rows,cols,str,row,col-1,len+1))return true;//左
if(col+1<cols && getPath(matrix,rows,cols,str,row,col+1,len+1))return true;//右
flags[currentNum] = false;//走到这一步说明该格子不符合,清空标志
return false;
}
}