LeetCode Solutions
994. Rotting Oranges
Time: $O(kmn)$ Space: $O(mn)$
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
const int m = grid.size();
const int n = grid[0].size();
const vector<int> dirs{0, 1, 0, -1, 0};
auto isNeighborRotten = [&](int i, int j, const vector<vector<int>>& grid) {
for (int k = 0; k < 4; ++k) {
const int r = i + dirs[k];
const int c = j + dirs[k + 1];
if (r < 0 || r == m || c < 0 || c == n)
continue;
if (grid[r][c] == 2)
return true;
}
return false;
};
int ans = 0;
while (true) {
vector<vector<int>> nextGrid(m, vector<int>(n));
// Calculate `nextGrid` based on `grid`
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (grid[i][j] == 1) { // Fresh
if (isNeighborRotten(
i, j, grid)) // Any of 4-directionally oranges is rotten
nextGrid[i][j] = 2;
else
nextGrid[i][j] = 1;
} else if (grid[i][j] == 2) { // Rotten
nextGrid[i][j] = 2; // Keep rotten
}
if (nextGrid == grid)
break;
grid = nextGrid;
++ans;
}
return any_of(
begin(grid), end(grid),
[&](vector<int>& row) {
return any_of(begin(row), end(row),
[&](int orange) { return orange == 1; });
})
? -1
: ans;
}
};
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
const int m = grid.size();
const int n = grid[0].size();
const vector<int> dirs{0, 1, 0, -1, 0};
int ans = 0;
int countFresh = 0;
queue<pair<int, int>> q;
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) {
const auto [i, j] = q.front();
q.pop();
for (int k = 0; k < 4; ++k) {
const int x = i + dirs[k];
const int y = j + dirs[k + 1];
if (x < 0 || x == m || y < 0 || y == n)
continue;
if (grid[x][y] != 1)
continue;
grid[x][y] = 2; // Mark grid[x][y] as rotten
q.emplace(x, y); // Push newly rotten orange to queue
--countFresh; // Decrease the count of fresh oranges by 1
}
}
}
return countFresh == 0 ? ans - 1 : -1;
}
};