题解 | #疯牛病II#

疯牛病II

https://www.nowcoder.com/practice/2d5c96e452a949e09d98bb32aec3b61d

class Solution {
  public:
    int healthyCowsII(vector<vector<int> >& pasture) {
        int dx[4] = {-1, 1, 0, 0};
        int dy[4] = {0, 0, 1, -1};
        int m = pasture.size(), n = pasture[0].size();
        queue<pair<int, int>> queue;
        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (pasture[i][j] == 2) queue.push({i, j});
                else if (pasture[i][j] == 1) count++;
            }
        }
        if (count == 0) return 0; //特判
        int flag;
        int min = 0;
        while (!queue.empty()) {
            int size = queue.size();
            flag = 0;
            for (int i = 0; i < size; i++) {
                auto [x, y] = queue.front();
                queue.pop();
                for (int j = 0; j < 4; j++) {
                    int ix = x + dx[j], iy = y + dy[j];
                    if (ix < 0 || ix >= m || iy < 0 || iy >= n || pasture[ix][iy] != 1) continue;
                    pasture[ix][iy] = 2;
                    queue.push({ix, iy});
                    count--;
                    flag = 1;  //标记这一分钟出现了感染,若该循环未出现感染则程序结束
                }
            }
            min++;
            if (count == 0) return min;
            if (!flag) return -1;
        }
        return count;
    }
};

全部评论

相关推荐

河和静子:如果大专也能好过的话,我寒窗苦读几年的书不是白读了?
点赞 评论 收藏
分享
10-05 11:11
海南大学 Java
投票
理想江南137:感觉挺真诚的 感觉可以试一试
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务