链接:
https://leetcode-cn.com/problems/rotting-oranges/
描述:
示例:
提示:
代码:
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
//用pair存放位置
queue<pair<int,int>> q;
int row = grid.size();
int col = grid[0].size();
//已经腐烂的橘子入队列
for(int i = 0;i<row;++i)
{
for(int j = 0;j<col;++j)
{
if(grid[i][j] == 2) q.push(make_pair(i,j));
}
}
//可以蔓延的方向:
static int nextp[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
int ret = 0;
//核心:
while(!q.empty())
{
int n = q.size();
int flag = 0;
while(n--)
{
auto Curpos = q.front();
q.pop();
for(int i = 0;i<4;i++)
{
int nx = Curpos.first + nextp[i][0];
int ny = Curpos.second+ nextp[i][1];
if(nx>=row || nx<0 || ny>=col || ny<0 || grid[nx][ny] != 1) continue;
flag = 1;
grid[nx][ny] = 2;
q.push(make_pair(nx,ny));
}
}
//如果有腐烂的
if(flag) ++ret;
}
//判断-1
for(int i = 0;i<row;++i)
{
for(int j = 0;j<col;++j)
if(grid[i][j] == 1) return -1;
}
return ret;
}
};