题目
思路
代码
class Solution {
int go[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public:
int orangesRotting(vector<vector<int>>& grid) {
int ans = 0, zero = 0, one = 0, len = 0;
std::queue< std::pair<int, int> >Q;
for (int i = 0; i < grid.size(); ++ i){
for (int j = 0; j < grid[0].size(); ++ j){
if (grid[i][j] == 2) Q.push(make_pair(i, j)); // 烂橘子入队!
else grid[i][j] ? ++ one : ++ zero; // 判断是好橘子🍊还是空地
}
}
if ((Q.empty() && one) || !one) return one ? -1 : 0; // 特判一下
while (!Q.empty() && one) {
len = Q.size(); // 🚩 确定循环次数
for (int k = 0; k < len; ++ k){
std::pair<int, int> p = Q.front(); Q.pop();
for (int i = 0; i < 4; ++ i){
int tx = p.first+go[i][0], ty = p.second+go[i][1];
if (tx >= 0 && tx < grid.size() && ty >= 0 && ty < grid[0].size()
&& grid[tx][ty] == 1){
-- one;
grid[tx][ty] = 2; // 类似标记一下是否访问过,不然下一次就会出现被重复感染的情况
Q.push(make_pair(tx, ty));
}
}
}
++ ans;
}
return one == 0 ? ans : -1;
}
};