Rotting Oranges

Multi-source BFS — seed the queue with all initially-rotten oranges and level-iterate; return the level when the queue empties.

Medium
Time O(m * n) Space O(m * n)
LeetCode
6 min read
bfs matrix multi-source

Problem#

Grid cells: 0 empty, 1 fresh, 2 rotten. Each minute, every fresh adjacent to a rotten becomes rotten. Return the minutes until no fresh remain, or -1 if some can’t rot.

Examples#

  • [[2,1,1],[1,1,0],[0,1,1]]4.
  • [[2,1,1],[0,1,1],[1,0,1]]-1; [[0,2]]0.

Constraints#

  • 1 <= m, n <= 10.

Approach#

Multi-source BFS. Seed the queue with all initially rotten cells. Track fresh count. Process level by level; on rotting a fresh neighbor, decrement fresh. Answer is the level count when queue empties; if any fresh remain at end, return -1.

Solution#

Rotting Oranges
class Solution {
public:
int orangesRotting(vector<vector<int>>& g) {
int m = g.size(), n = g[0].size(), fresh = 0;
queue<pair<int,int>> q;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j) {
if (g[i][j] == 1) ++fresh;
else if (g[i][j] == 2) q.push({i, j});
}
if (fresh == 0) return 0;
int dr[4] = {-1, 1, 0, 0}, dc[4] = {0, 0, -1, 1};
int minutes = 0;
while (!q.empty()) {
int sz = q.size();
bool changed = false;
while (sz--) {
auto [r, c] = q.front(); q.pop();
for (int k = 0; k < 4; ++k) {
int nr = r + dr[k], nc = c + dc[k];
if (nr < 0 || nr >= m || nc < 0 || nc >= n) continue;
if (g[nr][nc] != 1) continue;
g[nr][nc] = 2;
--fresh;
q.push({nr, nc});
changed = true;
}
}
if (changed) ++minutes;
}
return fresh == 0 ? minutes : -1;
}
};

Editorial#

Multi-source BFS naturally handles “spread simultaneously from all infected sources” — each level corresponds to one minute. Only increment minutes when a level actually rotted something to avoid an off-by-one.

Complexity#

  • Time: O(m * n).
  • Space: O(m * n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.