剑指offer-65-矩阵中的路径

题目

在这里插入图片描述

思路

利用回溯法
回溯算法概念:在许多递归问题当中,我们采取的方法都是穷尽所有的可能,从而找出合法的解。但是在某些情况下,当递归到某一层的时候,根据设置的判断条件,可以 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;
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值