《剑指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)

相关推荐
西瓜本瓜@2 小时前
在Android中如何使用Protobuf上传协议
android·java·开发语言·git·学习·android-studio
言之。2 小时前
别学了,打会王者吧
java·python·mysql·容器·spark·php·html5
机智的人猿泰山2 小时前
java kafka
java·开发语言·kafka
Algorithm15762 小时前
谈谈接口和抽象类有什么区别?
java·开发语言
细心的莽夫3 小时前
SpringCloud 微服务复习笔记
java·spring boot·笔记·后端·spring·spring cloud·微服务
264玫瑰资源库4 小时前
问道数码兽 怀旧剧情回合手游源码搭建教程(反查重优化版)
java·开发语言·前端·游戏
pwzs5 小时前
Java 中 String 转 Integer 的方法与底层原理详解
java·后端·基础
东阳马生架构5 小时前
Nacos简介—2.Nacos的原理简介
java
普if加的帕5 小时前
java Springboot使用扣子Coze实现实时音频对话智能客服
java·开发语言·人工智能·spring boot·实时音视频·智能客服
爱喝一杯白开水5 小时前
SpringMVC从入门到上手-全面讲解SpringMVC的使用.
java·spring·springmvc