65、矩阵中的路径

写一个递归函数即可。因为规定不能走已经走过的路,所以定义一个rows*cols大小的boolean数组,用来表示当前结点是否已经走过。在遍历过程中还要用到回溯,因为如果一条路没走下去,那么这条路就要把状态更新为没走过。

递归的终止条件:row<0,col<0,row>=rows,col>=cols,isvisted[row*cols+col]==true,str[len]!=matrix[row*cols+col]满足其中一个就返回false。如果遍历到了len==str.length-1都没有返回false,那么就返回true。

递归方式,由于说了路径可以上下左右,那么递归函数就分别有(row+1,col)(row-1,col)(row,col+1)(row,col-1)四种不同的情况。

public class Solution {
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
    {
        if(matrix==null||matrix.length==0||rows<1||cols<1){
            return false;
        }
        boolean[] isvisted=new boolean[rows*cols];
        for(boolean v:isvisted){
            v=false;
        }
        int len=0;
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                 if(dfs(matrix,rows,cols,i,j,len,str,isvisted)){
                     return true;
                 }
            }
        }
        return false;
    }
    public boolean dfs(char[] matrix,int rows,int cols,int row,int col,int len,char[] str,boolean[] isvisted){
        if(row<0||col<0||row>=rows||col>=cols||isvisted[row*cols+col]==true||str[len]!=matrix[row*cols+col]){
            return false;
        }
        if(len==str.length-1){
            return true;
        }
        boolean haspath=false;
        isvisted[row*cols+col]=true;
        haspath=dfs(matrix,rows,cols,row+1,col,len+1,str,isvisted)||dfs(matrix,rows,cols,row-1,col,len+1,str,isvisted)||
            dfs(matrix,rows,cols,row,col+1,len+1,str,isvisted)||dfs(matrix,rows,cols,row,col-1,len+1,str,isvisted);
        if(!haspath){
            isvisted[row*cols+col]=false;
        }
        return haspath;
    }


}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值