剑指 offer acwing 24机器人的运动范围 (BFS)

题面

在这里插入图片描述

题解

BFS 问题 ,注意判断rows 和 cols 为0 的情况,其他就是BFS模板

代码

class Solution {
public:
    
    //求横纵坐标各位数之和
    int get_sum(int x, int y) {
    
        int sum = 0;
        while (x) {
            sum += x % 10;
            x /= 10;
        }
        while (y) {
            sum += y % 10;
            y /= 10;
        }
        return sum;
    
    }
    
    int movingCount(int threshold, int rows, int cols) {
    
        if (!rows || !cols) return 0;  //边界情况
        int dx[4] = {1, -1, 0, 0};
        int dy[4] = {0, 0, 1, -1};
        //初始化点都没有走过
        vector<vector<bool>> st(rows, vector<bool>(cols, false));
        int res = 0;
        queue<pair<int, int>> q;
        q.push({0, 0});
        while (q.size()) {
            auto t = q.front();
            q.pop();
            int x = t.first, y = t.second;
            //已经走过或者是和大于给定范围
            if (st[x][y] || get_sum(x, y) > threshold) continue;
            res++;
            st[x][y] = true;  //标记已经
            for (int i = 0; i < 4; i++) {
                int a = x + dx[i], b = y + dy[i];
                if (a >= 0 && a < rows && b >= 0 && b < cols) {
                    q.push({a, b});
                }
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值