思路:
public class Solution { //注意迭代!
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
if(matrix==null||rows<=0||cols<=0||str==null)
return false;
if(str.length==0)
return true;
boolean[] visited=new boolean[rows*cols];
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++){
if(isHasPath(matrix,i,j,rows,cols,0,visited,str))
return true;
}
}
return false;
}
private boolean isHasPath(char[] matrix,int row,int col,int rows,int cols,int k,boolean[] visited,char[] str){
if(row<0 || row>=rows || col<0 || col>=cols || str[k]!=matrix[row*cols+col] || visited[row*cols+col]){
return false;
}
if(k==str.length-1){
return true;
}
visited[row*cols+col]=true; //表示访问过
if(isHasPath(matrix, row+1, col, rows, cols, k+1, visited, str) ||
isHasPath(matrix, row, col+1, rows, cols, k+1, visited, str) ||
isHasPath(matrix, row-1, col, rows, cols, k+1, visited, str) ||
isHasPath(matrix, row, col-1, rows, cols, k+1, visited, str)){
return true;
}
visited[row*cols+col]=false;
return false;
}
}
本文介绍了一种用于在矩阵中寻找特定路径的递归算法。该算法通过深度优先搜索(DFS)遍历矩阵,检查是否能从任意位置开始,按照给定顺序访问所有字符。文章详细解释了算法的实现思路,并提供了完整的Java代码示例。
792

被折叠的 条评论
为什么被折叠?



