使用BFS来解决,保存一个腐烂的橘子队列并记录新鲜橘子的数目,对每个腐烂橘子从四个方向进行查找,如果是新鲜的橘子,就将其变为腐烂,加入队列。当新鲜橘子数组为0时,直接返回。
class Solution {
private :
int dir[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
public:
int orangesRotting(vector<vector<int>>& grid) {
queue<pair<int, int>> que;
int fresh = 0;
for(int i = 0; i < grid.size(); i++){
for(int j = 0; j < grid[0].size(); j++){
if(grid[i][j] == 2){
que.push(make_pair(i, j));
}else if(grid[i][j] == 1){
fresh++;
}
}
}
int ans = 0;
while(!que.empty()){
int size = que.size();
if(fresh == 0){
return ans;
}
while(size--){
auto [x, y] = que.front();
que.pop();
for(int i = 0; i < 4; i++){
int newx = x + dir[i][0];
int newy = y + dir[i][1];
if(newx < 0 || newx >= grid.size() || newy < 0 || newy >= grid[0].size()) continue;
if(grid[newx][newy] == 1){
grid[newx][newy] = 2;
fresh--;
que.push(make_pair(newx, newy));
}
}
}
ans++;
}
return fresh > 0 ? -1 : ans;
}
};