24ロボット(BFS)を提供するオファーの可動域

トピック

ここに画像の説明を挿入します

回答

BFSの問題、行と列が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;
    }
};

おすすめ

転載: blog.csdn.net/qq_44791484/article/details/114987877