994. 腐烂的橘子https://leetcode.cn/problems/rotting-oranges/description/?envType=study-plan-v2&envId=top-100-liked广度优先遍历就完事儿~,最后的判断还有没有好橘子还能优化下,但问题不大。
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
queue<pair<int, int>> rotten_oranges;
for (int i=0; i < grid.size(); ++i) {
for (int j=0; j < grid[0].size(); ++j) {
if (grid[i][j] == 2) rotten_oranges.push({i, j});
}
}
int res = 0;
queue<pair<int, int>> temp;
while (!rotten_oranges.empty()) {
while (!rotten_oranges.empty()) {
int i = rotten_oranges.front().first;
int j = rotten_oranges.front().second;
rotten_oranges.pop();
if (i +1<grid.size() && grid[i+1][j] == 1) {
temp.push({i+1, j});
grid[i+1][j] = 2;
}
if (i -1 >= 0 && grid[i-1][j] == 1) {
temp.push({i-1, j});
grid[i-1][j] = 2;
}
if (j + 1< grid[0].size() && grid[i][j+1] == 1) {
temp.push({i, j+1});
grid[i][j+1] = 2;
}
if (j - 1 >=0 && grid[i][j-1] == 1) {
temp.push({i, j-1});
grid[i][j-1] = 2;
}
}
if (temp.empty()) break;
while (!temp.empty()) {
int i = temp.front().first;
int j = temp.front().second;
temp.pop();
rotten_oranges.push({i, j});
}
res ++;
}
for (vector<int> rows: grid) {
for (int i: rows) {
if (i == 1) return -1;
}
}
return res;
}
};