力扣问题:994. 腐烂的橘子
注意点:多源BFS写法(本质层序遍历)、move数组的使用
cpp
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int n = grid.size();
int m = grid[0].size();
int fresh = 0; // 记录未被遍历到的位置个数
queue<pair<int, int>> q;
vector<int> move = {-1, 0, 1, 0, -1};
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int type = grid[i][j];
if (type == 0)
continue;
if (type == 1)
fresh++;
if (type == 2)
q.push({i, j});
}
}
while (!q.empty() && fresh) {
ans++; // 步数加一
int count = q.size();
// 注意循环时机
for (int i = 1; i <= count; i++) {
auto current = q.front();
q.pop();
for (int j = 0; j < 4; j++) {
int x = current.first + move[j];
int y = current.second + move[j + 1];
if (x >= 0 && x < n && y >= 0 && y < m && grid[x][y] == 1) {
grid[x][y] = 2;
fresh--;
q.push({x, y});
}
}
}
}
return fresh != 0 ? -1 : ans;
}
};