Sword Finger Offer ------- Robot's range of motion

Insert picture description here

Topic link!

Idea: This
question is also a typical search question. You can write it in bfs or dfs. I use bfs here. I start from the point (0,0), and then start from this point to traverse the surroundings, usually Up and down, left and right, but this question can be reduced to down or right, and then use a two-dimensional array to mark the points, put the matching points in the queue, and then loop through it.

Code:

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;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/115079502