剑指offer——机器人运动的范围

题解:机器人运动的范围

题目描述

在这里插入图片描述

题目链接:
https://www.acwing.com/problem/content/22/

思路分析

  • 这道题是非常经典的BFS问题
  • 我们首先从(0,0)位置开始搜索,每次朝着上下左右四个方向开始搜索,扩展新的节点
  • 扩展新的节点需要满足以下的条件:
  • 之前没有遍历过的点用bool数组来判断
  • 不能走出边界
  • 横纵坐标之和小于给定值 k
  • 答案就是遍历过的合法的节点
  • 四个方向的数组 int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
  • 时间复杂度O(nm)

代码实现

class Solution 
{
public:
    int get_sum(pair<int, int> p) 
    {
        int s = 0;
        while (p.first) 
        {
            s += p.first % 10;
            p.first /= 10;
        }
        while (p.second) 
        {
            s += p.second % 10;
            p.second /= 10;
        }
        return s;
    }

    int movingCount(int threshold, int rows, int cols)
    {
        
        if(!rows||!cols) return 0;
   
        queue<pair<int,int>> q;
        vector<vector<bool>> st(rows, vector<bool>(cols, false));
        
        //四个方向的数组
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

        int res = 0;
        q.push({0, 0});
        while (q.size()) 
        {
            auto t = q.front();
            q.pop();
            if (st[t.first][t.second] || get_sum(t) > threshold) continue;
            res ++ ;
            st[t.first][t.second] = true;
            for (int i = 0; i < 4; i ++ ) 
            {
                int x = t.first + dx[i], y = t.second + dy[i];
                if (x >= 0 && x < rows && y >= 0 && y < cols) q.push({x, y});
            }
        }

        return res;

    }
};
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值