机器人的运动范围--回溯法(JAVA实现)

这篇博客探讨了如何使用回溯法解决机器人在m行n列网格中移动的问题,其中机器人不能进入行和列坐标数位之和超过k的格子。作者通过创建一个布尔数组避免重复计算,并利用两个栈记录坐标来确定机器人的运动范围,最终返回栈的大小作为可到达的格子数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路:
使用一个与矩阵等大小的布尔数组防止重复计算。用两个栈记录坐标,最后返回栈大小即为运动范围

package jianzhioffer;

import java.util.Stack;

public class MS13 {
    public static void main(String[] args) {
        int k = 18;
        int m = 5;
        int n = 5;
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        boolean[][] array = new boolean[m][n];
        stack1.push(0);
        stack2.push(0);
        array[0][0] = true;

        robot(k,stack1,stack2,array);
        System.out.println(stack1.size());
        while(!stack1.isEmpty()){
            System.out.println("("+stack1.pop()+","+stack2.pop()+")");
        }
    }
    public static void robot(int k,Stack<Integer> stack1,Stack<Integer> stack2,boolean[][] array){
        int i = stack1.peek();
        int j = stack2.peek();
        //向上找
        if (i>0&&!array[i-1][j]){
            array[i-1][j] = true;
            int numer = count(i-1,j);
            if (numer<=k) {
                stack1.push(i - 1);
                stack2.push(j);
                robot(k, stack1, stack2, array);
            }
        }
        //向下找
        if (i<array.length-1&&!array[i+1][j]){
            array[i+1][j] = true;
            int numer = count(i+1,j);
            if (numer<=k){
                stack1.push(i+1);
                stack2.push(j);
                robot(k, stack1, stack2, array);
            }
        }
        //向左找
        if (j>0&&!array[i][j-1]){
            array[i][j-1] = true;
            int numer = count(i,j-1);
            if (numer<=k){
                stack1.push(i);
                stack2.push(j-1);
                robot(k, stack1, stack2, array);
        }
        }
        //向右找
        if (j<array[0].length-1&&!array[i][j+1]){
            array[i][j+1] = true;
            int numer = count(i,j+1);
            if (numer<=k){
                stack1.push(i);
                stack2.push(j+1);
                robot(k, stack1, stack2, array);}
        }
    }
    public static int count(int i,int j){
        int res = 0;
        while (i!=0){
            res = res+i%10;
            i=i/10;
        }
        while (j!=0){
            res = res+j%10;
            j=j/10;
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值