思路:扫描矩阵中所有字符,以该字符为起点,检测是否存在路径;
需要注意的点:回溯过程需要“恢复现场”。为了确保检测过程中不会重复进入同一个格子,需要设置visited数组,向下递归检索时,需要设置当前位置状态为“已搜索”,向下递归结束之后,返回上一层需要恢复当前位置状态为“未搜索”。
public boolean hasPathCore(char[] matrix, int rows, int cols, int row, int col,
char[] str, int index, boolean[][] visited){
//检测完毕,说明存在路径
if(index>=str.length) return true;
if(row<0||row>=rows||col<0||col>=cols) return false;
boolean answer=false;
if(!visited[row][col]&&str[index]==matrix[row*cols+col]) {
//设置搜索状态
visited[row][col]=true;
answer=hasPathCore(matrix,rows,cols,row+1,col,str,index+1,visited)||
hasPathCore(matrix,rows,cols,row-1,col,str,index+1,visited)||
hasPathCore(matrix,rows,cols,row,col-1,str,index+1,visited)||
hasPathCore(matrix,rows,cols,row,col+1,str,index+1,visited);
//恢复搜索状态
visited[row][col]=false;
}
return answer;
}
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
boolean answer=false;
if(matrix==null||matrix.length==0||str==null||str.length==0) return answer;
boolean[][] visited=new boolean[rows][cols];
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
//对所有位置搜索路径
answer=hasPathCore(matrix,rows,cols,i,j,str,0,visited);
//一旦搜索成功,就返回true
if(answer) return answer;
}
}
return answer;
}