https://www.nowcoder.com/practice/54ab9865ce7a45968b126d6968a77f34?tpId=196&tqId=40529&ru=/exam/oj
从每个腐烂的苹果开始使用广度优先遍历(bfs)
class Solution {
int n, m;
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
vector<vector<bool>> vis;
public:
int rotApple(vector<vector<int> >& grid) {
// write code here
m = grid.size(), n = grid[0].size();
vis.assign(m, vector<bool>(n, false));
// 将腐烂苹果放进queue
queue<pair<int, int>> q;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 2) {
q.push({i, j});
}
}
}
int ret = 0;
// 一层一层的遍历,广度优先遍历
while (q.size()) {
int sz = q.size();
ret++;
while (sz--) {
auto [a, b] = q.front();
q.pop();
for (int k = 0; k < 4; ++k) {
int x = a + dx[k];
int y = b + dy[k];
if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && grid[x][y] == 1) {
vis[x][y] = true;
q.push({x, y});
}
}
}
}
// 判断是否有永不腐烂的苹果
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1 && !vis[i][j]) {
return -1;
}
}
}
return ret - 1;
}
};