剑指 Offer ------- 机器人的运动范围

在这里插入图片描述

题目链接!

思路:
这道题也是典型的搜索题,你可以用bfs或者dfs写都可以,我这里用的是bfs,就从(0,0)这个点出发,然后从这个点开始向周围遍历,一般是上下左右,但是这道题可以缩减为向下或者向右,然后用一个二维数组进行点的标记即可,把符合的点放入队列中,再循环遍历即可。

代码:

class Solution {
    
    
    // 计算 x 的数位之和
    int get(int x) {
    
    
        int res=0;
        for (; x; x /= 10) {
    
    
            res += x % 10;
        }
        return res;
    }
public:
    int movingCount(int m, int n, int k) {
    
    
        if (!k) return 1;
        queue<pair<int,int> > Q;
        // 向右和向下的方向数组
        int dx[2] = {
    
    0, 1};
        int dy[2] = {
    
    1, 0};
        vector<vector<int> > vis(m, vector<int>(n, 0));
        Q.push(make_pair(0, 0));
        vis[0][0] = 1;
        int ans = 1;
        while (!Q.empty()) {
    
    
            auto [x, y] = Q.front();
            Q.pop();
            for (int i = 0; i < 2; ++i) {
    
    
                int tx = dx[i] + x;
                int ty = dy[i] + y;
                if (tx < 0 || tx >= m || ty < 0 || ty >= n || vis[tx][ty] || get(tx) + get(ty) > k) continue;
                Q.push(make_pair(tx, ty));
                vis[tx][ty] = 1;
                ans++;
            }
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43743711/article/details/115079502
今日推荐