题解 | #疯牛病I#

疯牛病I

https://www.nowcoder.com/practice/2066902a557647ce8e85c9d2d5874086

考察的知识点:多维数组、队列;

解答方法分析:

  1. 创建一个空的有序列表queue,用来存储待传播的感染牛位置。
  2. 遍历二维数组pasture,找出初始的感染牛位置,将这些位置依插入到有序列表queue中。
  3. 循环执行以下步骤,直到有序列表queue为空或者传染的次数达到上限k:取出有序列表queue中的第一个牛的位置。遍历该牛的四个相邻位置。如果相邻位置合法且为健康牛,则将其感染标记为2,并插入到有序列表queue的合适位置。
  4. 统计二维数组pasture中健康牛的数量:创建一个整数变量res,初始化为0。遍历二维数组pasture的每个元素:如果元素为健康牛,则将res加1。
  5. 返回最终剩余的健康牛数量res。

所用编程语言:C++;

完整编程代码:↓

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pasture int整型vector<vector<>>
     * @param k int整型
     * @return int整型
     */
    int healthyCows(vector<vector<int> >& pasture, int k) {
        int m = pasture.size();
        int n = pasture[0].size();
        queue<pair<int, int>> q;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (pasture[i][j] == 2) {
                    q.push({i, j});
                }
            }
        }
        while (!q.empty() && k > 0) {
            k--;
            int size = q.size();
            for (int i = 0; i < size; i++) {
                int x = q.front().first;
                int y = q.front().second;
                q.pop();
                vector<pair<int, int>> directions = {{x - 1, y}, {x + 1, y}, {x, y - 1}, {x, y + 1}};
                for (auto& dir : directions) {
                    int newX = dir.first;
                    int newY = dir.second;
                    if (newX >= 0 && newX < m && newY >= 0 && newY < n &&
                            pasture[newX][newY] == 1) {
                        pasture[newX][newY] = 2;
                        q.push({newX, newY});
                    }
                }
            }
        }
        int res = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (pasture[i][j] == 1) {
                    res++;
                }
            }
        }
        return res;
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-23 14:10
码农索隆:成年人最直白的答复:已读不回
点赞 评论 收藏
分享
Lorn的意义:你这种岗位在中国现在要么牛马天天加班,要么关系户进去好吃好喝,8年时间,真的天翻地覆了,对于资本来说你就说一头体力更好的牛马,哎,退伍没有包分配你真的亏了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务