题解 | #疯牛病I#

疯牛病I

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

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pasture int整型vector<vector<>> 
     * @param k int整型 
     * @return int整型
     */
    vector<pair<int,int>> direction = {{1,0},{0,1},{-1,0},{0,-1}};
    int healthyCows(vector<vector<int> >& pasture, int k) 
    {
        // write code here
        int health_cows = 0;
        queue<pair<int,int>> unhealth_cow;
        for (int i = 0;i < pasture.size();++i)
        {
            for (int j = 0;j < pasture[0].size();++j)
            {
                if (pasture[i][j] == 2)
                {
                    unhealth_cow.push({i,j});
                }
                if (pasture[i][j] == 1)
                {
                    health_cows += 1;
                }
            }
        }
        if (health_cows == 0)
        {
            return 0;
        }

        while(!unhealth_cow.empty() && k-- && health_cows > 0)
        {
            int n = unhealth_cow.size();
            for (int i = 0;i < n;++i)
            {
                auto temp = unhealth_cow.front();
                unhealth_cow.pop();
                for (auto it : direction)
                {
                    int nextx = it.first + temp.first;
                    int nexty = it.second + temp.second;
                    if (nextx < 0 || nexty < 0 || nextx >= pasture.size() || nexty >= pasture[0].size())
                    {
                        continue;
                    }
                    else
                    {
                        if (pasture[nextx][nexty] == 0 || pasture[nextx][nexty] == 2)
                        {
                            continue;
                        }
                    }
                    pasture[nextx][nexty] = 2;
                    health_cows -= 1;
                    if (health_cows == 0)
                    {
                        break;
                    }
                    unhealth_cow.push({nextx,nexty});
                }
            }
        }
        return health_cows;
    }
};

这种题不是属于图论的吗?

全部评论

相关推荐

牛客773130651号:巨佬,简历模板换成上下的,左右的很烦,hr看着不爽。。。科大随便乱杀,建议能保研就保研,不行也得考一下 ,985硕去干算法,比开发强多了。开发许多双非都能搞,学历优势用不上,算法有门槛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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