#include <queue>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pasture int整型vector<vector<>>
     * @param k int整型
     * @return int整型
     */
    struct node {
        int x, y, z;
    };
    int dx[4] = {-1, 0, 1, 0};
    int dy[4] = {0, -1, 0, 1};
    int healthyCows(vector<vector<int> >& pasture, int k) {
        // write code here
        queue<node>qu;
        int n = pasture.size();
        int m = pasture[0].size();
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (pasture[i][j] == 2)
                    qu.push({i, j, k});
            }
        }
        while (qu.size()) {
            node e = qu.front();
            qu.pop();
            for (int i = 0; i < 4; ++i) {
                int nx = e.x + dx[i];
                int ny = e.y + dy[i];
                if (nx >= 0 && ny >= 0 && nx < n && ny < m && pasture[nx][ny] == 1) {
                    pasture[nx][ny] = 2;
                    if (e.z - 1 > 0)
                        qu.push({nx, ny, e.z - 1});
                }
            }
        }
        int ans = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (pasture[i][j] == 1)
                    ++ans;
            }
        }
        return ans;
    }
};

一、题目考察的知识点

bfs

二、题目解答方法的文字分析

首先定义一结构体去存储所有满足要求的牛,然后依次从四个方向去遍历,但是不能超出范围,遇到未被传染的牛九把它标记为2,这里要注意k的情况,不能单独用一k去遍历所有的牛,因为被传染的牛也会向四周传染,所以每一个牛应该都有属于自己的k,当自己的k没有了,那么就不能传染了

三、本题解析所用的编程语言

c++