题目:
代码(2023年10月26日 首刷自解):
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
/*统计grid二维数组中有多少新鲜橘子和多少烂橘子,将所有的烂橘子存入一个三元队列中
其中,队列前两个参数表示烂橘子坐标,第三个参数代表是第几代烂橘子
同时,统计新鲜橘子数量*/
int m = grid.size();
int n = grid[0].size();
int fresh=0;
queue<tuple<int,int,int>> q;
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.emplace(i,j,0);//将烂橘子存入队列,第三个参数0表示都是最初的烂橘子
}
}
}
vector<int> dx ={1,0,-1,0};
vector<int> dy ={0,1,0,-1};
int time =0;//记录队列最后一个烂橘子是第几代
while(!q.empty()){
auto [cx,cy,d]=q.front();
time=d;
q.pop();
for(int i=0;i<4;++i){
int nx=cx+dx[i];
int ny=cy+dy[i];
//检查烂橘子四个方向上的是否在二维数组内部且是否是新鲜橘子
if(nx>=0 && nx<m && ny>=0 && ny<n &&grid[nx][ny]==1){
grid[nx][ny]=2;//将其变成烂橘子
fresh--;//新鲜橘子减少
q.emplace(nx,ny,d+1);//将烂橘子存入队列,并且标记其是第几代烂橘子
}
}
}
if(fresh>0){
return -1;
}else{
return time;
}
}
};
代码(二刷瞄了眼思路 2024年3月7日)
class Solution {
public:
void BFS(vector<vector<int>>& grid, int row, int column, queue<pair<int,int>>& q) {
int nr = grid.size();
int nc = grid[0].size();
if (row - 1 >= 0 && grid[row - 1][column] == 1)
{ grid[row-1][column] = 2; q.push(make_pair(row - 1, column));}
if (row + 1 < nr && grid[row + 1][column] == 1)
{ grid[row+1][column] = 2; q.push(make_pair(row + 1, column));}
if (column - 1 >= 0 && grid[row][column - 1] == 1)
{ grid[row][column - 1] = 2; q.push(make_pair(row, column - 1));}
if (column + 1 < nc && grid[row][column + 1] == 1)
{ grid[row][column + 1] = 2; q.push(make_pair(row, column + 1));}
}
int orangesRotting(vector<vector<int>>& grid) {
int nr = grid.size();
if (nr == 0) return 0;
int nc = grid[0].size();
queue<pair<int,int>> q;
int orange = 0;
for (int i = 0; i < nr; ++i) {
for (int j = 0; j < nc; ++j) {
if (grid[i][j] == 1 || grid[i][j] == 2) orange++;
if (grid[i][j] == 2) {
q.push(make_pair(i, j));
}
}
}
int time = 0;
int toxic_orange = 0;
while (!q.empty()) {
int size = q.size();
while (size--) {
auto it = q.front();
toxic_orange++;
q.pop();
BFS(grid, it.first, it.second, q);
}
time++;
}
if (time) time--;
return orange == toxic_orange ? time : -1;
}
};