题解 | #疯牛病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;
    }
};

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

全部评论

相关推荐

Southyeung:我说一下我的看法(有冒犯实属抱歉):(1)简历不太美观,给我一种看都不想看的感觉,感觉字体还是排版问题;(2)numpy就一个基础包,机器学习算法是什么鬼?我感觉你把svm那些写上去都要好一点。(2)课程不要写,没人看,换成获奖经历;(3)项目太少了,至少2-3个,是在不行把网上学习的也写上去。
点赞 评论 收藏
分享
LemontreeN:有的兄弟有的我今天一天面了五场,4个二面一个hr面
投递字节跳动等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务