298 字
1 分钟
Day20260312

Day20260312#

腐烂的橘子#

在给定的 m x n 网格 grid 中,每个单元格可以有以下三个值之一:

值 0 代表空单元格; 值 1 代表新鲜橘子; 值 2 代表腐烂的橘子。 每分钟,腐烂的橘子 周围 4 个方向上相邻 的新鲜橘子都会腐烂。

返回 直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1 。

题解#

一个简单的bfs。

class Solution {
int cnt;
int dis[10][10];
int dir_x[4] = {0, 1, 0, -1};
int dir_y[4] = {1, 0, -1, 0};
public:
int orangesRotting(vector<vector<int>>& grid) {
queue<pair<int, int>>Q;
memset(dis, -1, sizeof(dis));
cnt = 0;
int n = (int)grid.size(), m = (int)grid[0].size(), ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] == 2) {
Q.emplace(i, j);
dis[i][j] = 0;
}
else if (grid[i][j] == 1) {
cnt += 1;
}
}
}
while (!Q.empty()){
auto [r, c] = Q.front();
Q.pop();
for (int i = 0; i < 4; ++i) {
int tx = r + dir_x[i];
int ty = c + dir_y[i];
if (tx < 0|| tx >= n || ty < 0|| ty >= m || ~dis[tx][ty] || !grid[tx][ty]) {
continue;
}
dis[tx][ty] = dis[r][c] + 1;
Q.emplace(tx, ty);
if (grid[tx][ty] == 1) {
cnt -= 1;
ans = dis[tx][ty];
if (!cnt) {
break;
}
}
}
}
return cnt ? -1 : ans;
}
};
Day20260312
https://blog.eachic.me/posts/hot100/day20260312/
作者
Eachic
发布于
2026-03-12
许可协议
CC BY-NC-SA 4.0