994. 腐烂的橘子
题目地址 :994. 腐烂的橘子 - 力扣(LeetCode)
题解思路:bfs
时间复杂度:O(mn)
空间复杂度:O(mn)
代码:
cpp
class Solution {
public:
int dir[4][2] = {-1, 0, 1, 0, 0, -1, 0, 1};
int orangesRotting(vector<vector<int>>& grid) {
// bfs
int m = grid.size(), n = grid[0].size();
int fresh = 0;
queue<pair<int, int>>q; // 存储栏橘子的位置
// 第0分钟
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(grid[i][j] == 1){
fresh++;
} else if (grid[i][j] == 2){
q.push({i, j});
}
}
}
int ret = 0;
while(!q.empty()){
int size = q.size();
bool flag = false;
for(int i = 0; i < size; i++){
auto [x, y] = q.front();
q.pop();
for(int i = 0; i < 4; i++){
int next_x = x + dir[i][0], next_y = y + dir[i][1];
if(next_x < 0 || next_x >= m || next_y < 0 || next_y >= n){
continue;
}
if(grid[next_x][next_y] == 1){
grid[next_x][next_y] = 2;
q.push({next_x, next_y});
fresh--;
flag = true;
}
}
}
if(flag){
ret++;
}
}
return fresh ? -1 : ret;
}
};