题解 | #疯牛病I#

疯牛病I

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

#include <queue>
#include <utility>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pasture int整型vector<vector<>> 
     * @param k int整型 
     * @return int整型
     */


    int healthyCows(vector<vector<int> >& pasture, int k) {
        // write code here
        int m = pasture.size();
        int n = pasture[0].size();
        queue<pair<int,int>> que;
        vector<pair<int,int>> moves={{-1,0},{1,0},{0,-1},{0,1}};
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(pasture[i][j] == 2){
                    que.push(make_pair(i,j));//放入疯牛病的坐标
                }
            }
        }
        int minute=0;
        while(!que.empty() && minute < k){
            int N = que.size();
            for(int i=0;i<N;i++){
                pair<int,int> point = que.front();
                que.pop();
                int x = point.first;
                int y = point.second;
                for(auto move:moves){
                    int nx = x + move.first;
                    int ny = y + move.second;
                    if(nx>=0 && nx<m && ny>=0 && ny<n && pasture[nx][ny]==1){
                        pasture[nx][ny]=2;
                        que.push(make_pair(nx,ny));
                    }
                }
            }
            minute++;
        }
        int count = 0;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(pasture[i][j] == 1){
                    count++;
                }
            }
        }
        return count;
    }
};

dfs模拟上下左右扩散

全部评论

相关推荐

07-19 13:28
长沙学院 Java
鸿哥鸿哥:学院(一本),感觉在脱ku子放屁,学院结尾的除了那几家出名的,一律按二本处理
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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