动态规划之机器人的移动范围的回溯算法

本文分享了如何使用动态规划解决机器人移动限制问题,通过优化递归结构避免大数级递归带来的效率问题。重点介绍了getNumber函数、visit数组和check方法的应用,并探讨了如何处理大矩阵场景下的性能提升策略。
摘要由CSDN通过智能技术生成

动态规划之机器人的移动范围的回溯算法心得

要想解决这个问题首先要理清思路
题目:地上有一个M行N列的方格,一个机器人从坐标0,0的格子开始移动,每次可以向左右上下移动一格,但不能进入航坐标和列坐标的位数之和,大于K的格子列入,当K为18时,机器人能够进入方格35 ,37,因为3+5+3+7=18,但它不能进入方格35 ,38,因为3+5+3+8=19,请问该机器人能够到达多少个格子?
首先,机器人得移动方格会受限制不能大于行坐标和列坐标得位数之和;因此首先要计算出各个位上得数然后求和,这里我定义了一个函数getNumber(int n) 来获取位数和;

   public int getNumber(int n){
        int res = 0;
        if(n>0){
            res = res+n%10;
            n=n/10;
        }
        return res;
    }

第二点,如果某行某列已经走过了,那么我们就要标记一下;我定义了一个布尔数组来存储标记;

boolean[] visit =new boolean[rows*cows]; 

第三点,要通过校验,获取当前的下一个遍历路径,通过check()来实现;

   public boolean check(int threshold,int rows,int cols,int row,int col,boolean[] visit){
            if(row>=0&&row<rows&&col>=0&&col<cols&&(getNumber(row)+getNumber(col))<=threshold && !visit[row*cols+col]){
                return true;
            }
            return false;
        }

结合上述步骤,可以完美解决问题;代码如下;

public class Demo {
    public static void main(String[] args) {

        int rows =50;
        int cows =50;
        int num = 62;

        Demo sb = new Demo();
        System.out.println(sb.movingCount(num, rows, cows));


    }

    int getNumber(int n){
        int res = 0;
        if(n>0){
            res = res+n%10;
            n=n/10;
        }
        return res;
    }

        public int movingCount(int threshold, int rows, int cols) {
            if(threshold<0||rows<=0||cols<=0) return  0;
            boolean[] visit = new boolean[rows*cols];
            for (int i=0;i<rows*cols;i++){
                visit[i] = false;}
            int count = movinggo(threshold, rows, cols, 0, 0, visit);
            return count;
        }


        public int movinggo(int threshold,int rows,int cols,int row,int col,boolean[] visit){
            int count = 0;
            if(check(threshold, rows, cols, row, col, visit)){
                visit[row*cols+col]=true;
                count= 1+movinggo(threshold, rows, cols, row+1, col, visit)
                        +movinggo(threshold, rows, cols, row, col-1, visit)
                        +movinggo(threshold, rows, cols, row-1, col, visit)
                        +movinggo(threshold, rows, cols, row, col+1, visit);
            }
            return count;
        }

        public boolean check(int threshold,int rows,int cols,int row,int col,boolean[] visit){
            if(row>=0&&row<rows&&col>=0&&col<cols&&(getNumber(row)+getNumber(col))<=threshold && !visit[row*cols+col]){
                return true;
            }
            return false;
        }
    }



缺点:如果行和列很大,递归会非常慢,程序可能会崩溃;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沉默着忍受

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值