机器人的运动范围详解DFS策略

不多bb,直接看代码

public class RobotMovingScopeCount {
    public static void main(String[] args) {
        /*
         *注意:对于矩阵问题,创建一个与矩阵相同的二维数组作为辅助变量是常见做法
         */
        //传入参数
        int threshold = 15;
        int rows = 20;
        int cols = 20;
        //使用二维数组保存机器人经过的格子
        int[][] blocksPassed = new int[rows][cols];
        //将二维数组所有元素初始化为-1
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                blocksPassed[i][j] = -1;
            }
        }

        countWithDFS(blocksPassed,threshold,rows,cols,0,0);

        //统计blocksPassed中值为1的元素数目,即为符合要求的格子数
        int count = 0;
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                if(blocksPassed[i][j] == 1){
                    count += 1;
                }
            }
        }
        System.out.println(count);
    }

    /*
     *DFS策略:
     *dfs(){
     *    第一步,检查下标
     *    第二步,检查是否被访问过,或者是否满足当前匹配条件
     *    第三步,检查是否满足返回结果条件
     *    第四步,都没有返回,说明应该进行下一步递归,步骤:标记、dfs()、回溯
     * }
     */
    public static boolean countWithDFS(int[][] blocksPassed,int threshold, int rows, int cols, int i, int j){
        //递归终止条件
        if(i<0 || rows <= i || j<0 || cols <= j){
            return true;
        }
        if(blocksPassed[i][j] == 1){
            return true;
        }
        if((sumOfInteger(i)+sumOfInteger(j)) > threshold){
            return true;
        }
        //格子(i,j)满足要求,将blocksPassed[i][j]标记为1
        blocksPassed[i][j] = 1;
        //下一级递归
        return  countWithDFS(blocksPassed,threshold,rows,cols,i+1,j)&&
                countWithDFS(blocksPassed,threshold,rows,cols,i-1,j)&&
                countWithDFS(blocksPassed,threshold,rows,cols,i,j+1)&&
                countWithDFS(blocksPassed,threshold,rows,cols,i,j-1);
    }


    public static int  sumOfInteger(int num){
        int num1 = num/1000;
        int num2 = (num%1000)/100;
        int num3 = (num%100)/10;
        int num4 = num%10;
        return num1+num2+num3+num4;
    }
}

以上均为个人见解,如有谬误,欢迎指正!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值