class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int total = 0;
int m = grid.size();
int n = grid[0].size();
deque<pair<int, int>> queue;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(grid[i][j] == 1){
total++;
}else if(grid[i][j] == 2){
queue.push_back({i, j});
}
}
}
int depth = 0;
while(total > 0 && !queue.empty()){
int size = queue.size();
while(size--){
pair<int, int> cur = queue.front();
queue.pop_front();
int i = cur.first;
int j = cur.second;
if(i > 0 && grid[i - 1][j] == 1){
grid[i - 1][j] = 2;
total--;
queue.push_back({i - 1, j});
}
if(i + 1 < m && grid[i + 1][j] == 1){
grid[i + 1][j] = 2;
total--;
queue.push_back({i + 1, j});
}
if(j > 0 && grid[i][j - 1] == 1){
grid[i][j - 1] = 2;
total--;
queue.push_back({i, j - 1});
}
if(j + 1 < n && grid[i][j + 1] == 1){
grid[i][j + 1] = 2;
total--;
queue.push_back({i, j + 1});
}
}
depth++;
}
if(total != 0) return -1;
return depth;
}
};
08-20
537
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-20
423
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)