In a given grid, each cell can have one of three values:
- the value 0 representing an empty cell;
- the value 1 representing a fresh orange;
- the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead.
简单来说,就是网格中0表示空,1表示新鲜水果,2表示腐烂水果,每个腐烂水果能在一分钟之后把与它相邻(上下左右)的新鲜水果变烂,问至少需要多长时间所有水果变烂。
本文采用BFS遍历,借助queue<vector>
存储腐烂苹果
- 从腐烂位置遍历四个方向,将新一轮的腐烂苹果入队
- 向queue里push时要考虑不能添加已经遍历过的位置
- 记录起始新鲜水果个数,判断是否有孤立水果(return -1)
int orangesRotting(vector<vector<int>>& grid) {
//广度优先搜索遍历
int fresh = 0,rot = 0,ans=0;
int row = grid.size();
int col = grid[0].size();
int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};
queue<vector<int>> queRot;
vector<int> tmpRot;
for(int i = 0;i < row;i++)
{
for(int j = 0;j < col;j++)
{
if(grid[i][j] == 1) fresh++;
if(grid[i][j] == 2)
{
rot++;
queRot.push({i,j});
}
}
}
while(!queRot.empty())
{
int curRot = rot;
rot = 0;
while(curRot--)
{
tmpRot = queRot.front();
queRot.pop();
int x,y;
for(int i = 0;i < 4;i++)
{
x = tmpRot[0] + dx[i];
y = tmpRot[1] + dy[i];
if(x<0||y<0||x>=row||y>=col||grid[x][y]!=1) continue;
grid[x][y] = 2;
queRot.push({x,y});
fresh--;
rot++;
}
}
ans++;
}
if(fresh) return -1;
else return max(0,ans-1);
}
int main(){
//case1: { {2,1,1},{1,1,0},{0,1,1} }
vector<vector<int> >test1 = { {2,1,1},{1,1,0},{0,1,1} };
cout << orangesRotting(test1) << endl;
//case2: {{2,1,1},{0,1,1},{1,0,1}}
vector<vector<int> >test2 = { { 2,1,1 },{ 0,1,1 },{ 1,0,1 } };
cout << orangesRotting(test2) << endl;
return 0;
}