广度优先搜索,并且腐烂是一圈同时腐烂,所以可以抽象理解成层序遍历一层节点全部遍历(确实抽象……)
#include<vector>
#include<queue>
#include <iostream>
using namespace std;
class Solution {
private:
int dir[4][2] = { -1,0,0,-1,1,0,0,1 };
public:
int orangesRotting(vector<vector<int>>& grid) {
int maxc = 0;//烂掉的分钟数
int fresh = 0;//新鲜的水果
queue<pair<int, int>>que;//存放烂了的水果的位置
//先统计烂水果和新鲜水果
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
if (grid[i][j] == 2)
{
que.push({ i,j });
}
else if (grid[i][j] == 1)
{
fresh++;
}
}
}
maxc = -1;//第一个是本来就烂的,不是被感染的
while (!que.empty()) {
maxc++;
int size = que.size();//相当于二叉树层序遍历,因为每一圈水果是同时烂的,这一圈的时间是一样的
//将这一圈全部感染,广度优先
for (int i = 0; i < size; i++)
{
pair<int, int>cur = que.front();
que.pop();
int curx = cur.first;
int cury = cur.second;
for (int i = 0; i < 4; i++)
{
int nextx = curx + dir[i][0];
int nexty = cury + dir[i][1];
if (nextx < 0 || nexty < 0 || nextx >= grid.size() || nexty >= grid[0].size())//越界跳过
continue;
if (grid[nextx][nexty] == 1)
{
que.push({ nextx,nexty });
grid[nextx][nexty] = 2;
fresh--;//新鲜水果被感染了
}
}
}
}
maxc = max(0, maxc);
return fresh ? -1 : maxc;
}
};
int main()
{
vector<vector<int>>grid = {
{2,1,1 }, {1, 1, 0}, {0, 1, 1}
};
Solution solution;
int result = solution.orangesRotting(grid);
cout << result << endl;
}