链接:https://leetcode-cn.com/problems/rotting-oranges/
来源:LeetCode
思路:先判断给出的图中是否有新鲜的橘子,如果没有就输出 0,其次用
b
f
s
bfs
bfs 求出每个腐烂的橘子到其邻近新鲜橘子的距离(优先队列每次取出最小的花费的点去更新其他点的距离)。实现
b
f
s
bfs
bfs 的时候注意代码不要写错(执行出错一般是因为数组越界)。
class Solution {
public:
struct Node {
int x, y, cost;
Node(){}
Node(int x, int y, int cost) : x(x), y(y), cost(cost) {}
bool operator < (const Node & node) const {
return cost > node.cost;
}
};
void bfs(vector<vector<int>>& grid, vector<vector<int>>& step) {
int n = grid.size(), m = grid[0].size();
vector<vector<int>> vis(n, vector<int>(m, false));
int net[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
priority_queue<Node>pq;
for (int i = 0; i < n; i ++) {
for(int j = 0; j < m; j ++) {
if (grid[i][j] == 2) pq.push(Node(i, j, 0));
}
}
while (!pq.empty()) {
Node now = pq.top(); pq.pop();
if (vis[now.x][now.y]) continue;
step[now.x][now.y] = now.cost;
vis[now.x][now.y] = true;
for (int i = 0; i < 4; i ++) {
int netx = now.x + net[i][0];
int nety = now.y + net[i][1];
if (netx < 0 || netx >= n || nety < 0 || nety >= m)
continue;
if (grid[netx][nety] == 0 ) vis[netx][nety] = true;
if (vis[netx][nety]) continue;
if (grid[netx][nety] == 1) {
pq.push(Node(netx, nety, now.cost + 1));
} else if (grid[netx][nety] == 2) {
pq.push(Node(netx, nety, 0));
}
}
}
}
int orangesRotting(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
int cnt1 = 0;
for (int i = 0; i < n; i ++) {
for(int j = 0; j < m; j ++) {
if (grid[i][j] == 1) cnt1 ++;
}
}
if (cnt1 == 0) return 0;
vector<vector<int>> step(n, vector<int>(m, 0));
bfs(grid, step);
int Max = -1;
bool flag = false;
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
if (grid[i][j] == 1 && step[i][j] == 0) {
flag = true;
break;
}
if (Max < step[i][j]) Max = step[i][j];
}
}
if (flag) Max = -1;
return Max;
}
};