2024每日刷题(136)
Leetcode—994. 腐烂的橘子
实现代码
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
queue<pair<int, int>> q;
int ans = 0;
constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int m = grid.size();
int n = grid[0].size();
int countFresh = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == 1) {
countFresh++;
} else if(grid[i][j] == 2) {
q.emplace(i, j);
}
}
}
if(countFresh == 0) {
return 0;
}
while(!q.empty()) {
ans++;
for(int sz = q.size(); sz > 0; sz--) {
auto [i, j] = q.front();
q.pop();
for(auto &[dx, dy]: dirs) {
int x = i + dx;
int y = j + dy;
if(x < 0 || x == m || y == n || y < 0) {
continue;
}
if(grid[x][y] != 1) {
continue;
}
grid[x][y] = 2;
countFresh--;
q.emplace(x, y);
}
}
}
return ans = (countFresh > 0) ? -1 : ans - 1;
}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!