题解 | #疯牛病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; } };
这种题不是属于图论的吗?