题目描述:
In a given grid, each cell can have one of three values:
- the value
0representing an empty cell; - the value
1representing a fresh orange; - the value
2representing 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.
Example 1:

Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2:
Input: [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Note:
1 <= grid.length <= 101 <= grid[0].length <= 10grid[i][j]is only0,1, or2.
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
// 考虑没有烂橘子和全是烂橘子的情况,同时记录新鲜橘子个数
int m=grid.size(), n=grid[0].size();
int fresh_count=0;
queue<pair<int,int>> q;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(grid[i][j]==1) fresh_count++;
if(grid[i][j]==2) q.push({i,j});
}
}
if(fresh_count==0) return 0;
if(q.size()==0) return -1;
int minute=0;
vector<pair<int,int>> dirs={{0,1},{0,-1},{1,0},{-1,0}};
while(!q.empty())
{
int x=q.size();
int rotten_count=0;
for(int k=0;k<x;k++)
{
int i=q.front().first, j=q.front().second;
q.pop();
for(auto dir:dirs)
{
int x=i+dir.first, y=j+dir.second;
if(x>=0&&x<m&&y>=0&&y<n&&grid[x][y]==1)
{
rotten_count++;
grid[x][y]=2;
q.push({x,y});
}
}
}
minute++;
fresh_count-=rotten_count;
if(fresh_count==0) return minute;
}
return -1;
}
};
本文介绍了一种基于网格的烂橘子扩散算法,通过遍历二维数组,利用队列实现橘子腐烂过程的模拟,旨在计算所有新鲜橘子完全腐烂所需的最短时间。文章详细解析了算法流程,包括初始化橘子状态、腐烂橘子扩散以及最终结果判断。
646

被折叠的 条评论
为什么被折叠?



