《剑指offer》Java版--13.机器人的运动范围(BFS)

剑指offer原题13:机器人的运动范围

地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动,它每次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7=18。但它不能进入方格(35,38),因为3+5+3+8=19。请问该机器人能够到达多少个格子?

LeetCode原题:https://leetcode.cn/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/description/

java 复制代码
class Solution {
    public int wardrobeFinishing(int m, int n, int cnt) {
        // ps:这是力扣题目有点不一样,方向只有两个。
        int[][] dir = new int[][]{{1, 0}, {0, 1}};
        boolean[][] vis = new boolean[m][n];
        LinkedList<Pair<Integer, Integer>> queue = new LinkedList<>();
        queue.push(new Pair<>(0, 0));
        int res = 0;
        while(queue.size() > 0) {
            Pair<Integer, Integer> pair = queue.pollFirst();
            vis[pair.getKey()][pair.getValue()] = true;
            res++;
            for(int i = 0; i < 2; ++i) {
                int nextX = pair.getKey() + dir[i][0];
                int nextY = pair.getValue() + dir[i][1];
                if(nextX >= 0 && nextX < m && nextY >= 0 && nextY < n
                        && !vis[nextX][nextY]
                        && digitalSum(nextX) + digitalSum(nextY) <= cnt) {
                    queue.push(new Pair<>(nextX, nextY));
                }
            }
        }
        return res;
    }

    private int digitalSum(int x) {
        int res = 0;
        while(x > 0) {
            res += x % 10;
            x /= 10;
        }
        return res;
    }
}

时间复杂度O(NM)

空间复杂度O(NM)

相关推荐
我命由我1234522 分钟前
Java 并发编程 - Delay(Delayed 概述、Delayed 实现、Delayed 使用、Delay 缓存实现、Delayed 延迟获取数据实现)
java·开发语言·后端·缓存·java-ee·intellij-idea·intellij idea
北城以北888823 分钟前
SSM--MyBatis框架之缓存
java·缓存·intellij-idea·mybatis
kyle~28 分钟前
算法数学---差分数组(Difference Array)
java·开发语言·算法
曹朋羽34 分钟前
Spring EL 表达式
java·spring·el表达式
沐浴露z1 小时前
详解JDK21新特性【虚拟线程】
java·开发语言·jvm
No0d1es1 小时前
电子学会青少年软件编程(C/C++)1级等级考试真题试卷(2025年9月)
java·c语言·c++·青少年编程·电子学会·真题·一级
9号达人2 小时前
普通公司对账系统的现实困境与解决方案
java·后端·面试
超级苦力怕2 小时前
Java 为何 long a = 999999999 能过;long a = 9999999999 报错?一文讲透“宽化转换”
java
佐杰2 小时前
Jenkins使用指南1
java·运维·jenkins
dllxhcjla2 小时前
三大特性+盒子模型
java·前端·css