Rotting Oranges
Rotting Oranges is a medium graphs problem solved with the multi source bfs pattern.
The best approach, optimal (multi-source bfs), runs in O(m · n) time and O(m · n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from simulate minute by minute up.
Problem
Each minute, every fresh orange (1) next to a rotten one (2) becomes rotten. Return the minimum number of minutes until no fresh orange is left, or -1 if that never happens.
Examples
Example 1
- Input
grid = [[2,1,1],[1,1,0],[0,1,1]]- Output
4
Example 2
- Input
grid = [[2,1,1],[0,1,1],[1,0,1]]- Output
-1- Why
- The bottom-left orange can never be reached.
Constraints
1 <= m, n <= 10; 0 = empty, 1 = fresh, 2 = rotten.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Simulate minute by minute | O((m · n)²) | O(m · n) |
| Optimal (multi-source BFS) | O(m · n) | O(m · n) |
1Simulate minute by minute
O((m · n)²)O(m · n)Each minute, scan the grid and rot every fresh orange next to a rotten one. Stop when nothing changes.
- Repeat: collect fresh cells adjacent to rotten ones; rot them; minutes++.
- If no change: return minutes if no fresh remain, else -1.
class Solution {
public int orangesRotting(int[][] grid) {
int m = grid.length, n = grid[0].length, minutes = 0;
int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
while (true) {
List<int[]> next = new ArrayList<>();
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if (grid[i][j] != 1) continue;
for (int[] d : dirs) {
int r = i + d[0], c = j + d[1];
if (r >= 0 && c >= 0 && r < m && c < n && grid[r][c] == 2) { next.add(new int[] { i, j }); break; }
}
}
if (next.isEmpty()) break;
for (int[] p : next) grid[p[0]][p[1]] = 2;
minutes++;
}
for (int[] row : grid) for (int x : row) if (x == 1) return -1;
return minutes;
}
}class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
m, n, minutes = len(grid), len(grid[0]), 0
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
while True:
nxt = []
for i in range(m):
for j in range(n):
if grid[i][j] != 1:
continue
for d in dirs:
r, c = i + d[0], j + d[1]
if r >= 0 and c >= 0 and r < m and c < n and grid[r][c] == 2:
nxt.append((i, j))
break
if not nxt:
break
for p in nxt:
grid[p[0]][p[1]] = 2
minutes += 1
for row in grid:
for x in row:
if x == 1:
return -1
return minutesclass Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size(), minutes = 0;
int dirs[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
while (true) {
vector<pair<int, int>> next;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if (grid[i][j] != 1) continue;
for (auto& d : dirs) {
int r = i + d[0], c = j + d[1];
if (r >= 0 && c >= 0 && r < m && c < n && grid[r][c] == 2) { next.push_back({i, j}); break; }
}
}
if (next.empty()) break;
for (auto& p : next) grid[p.first][p.second] = 2;
minutes++;
}
for (auto& row : grid) for (int x : row) if (x == 1) return -1;
return minutes;
}
};function orangesRotting(grid) {
const m = grid.length, n = grid[0].length;
let minutes = 0;
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
while (true) {
const next = [];
for (let i = 0; i < m; i++)
for (let j = 0; j < n; j++) {
if (grid[i][j] !== 1) continue;
for (const d of dirs) {
const r = i + d[0], c = j + d[1];
if (r >= 0 && c >= 0 && r < m && c < n && grid[r][c] === 2) { next.push([i, j]); break; }
}
}
if (next.length === 0) break;
for (const p of next) grid[p[0]][p[1]] = 2;
minutes++;
}
for (const row of grid) for (const x of row) if (x === 1) return -1;
return minutes;
}2Optimal (multi-source BFS)
O(m · n)O(m · n)Enqueue every rotten orange at time 0 and count the fresh ones. BFS level by level; each level is one minute. When a fresh orange rots, decrement the fresh count.
- Queue all 2s; fresh = count of 1s.
- While the queue is not empty and fresh > 0: process one level, rotting neighbours; minutes++.
- Return fresh == 0 ? minutes : -1.
class Solution {
public int orangesRotting(int[][] grid) {
int m = grid.length, n = grid[0].length, fresh = 0, minutes = 0;
Queue<int[]> q = new ArrayDeque<>();
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if (grid[i][j] == 2) q.add(new int[] { i, j });
else if (grid[i][j] == 1) fresh++;
}
int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
while (!q.isEmpty() && fresh > 0) {
for (int s = q.size(); s > 0; s--) {
int[] c = q.poll();
for (int[] d : dirs) {
int r = c[0] + d[0], k = c[1] + d[1];
if (r >= 0 && k >= 0 && r < m && k < n && grid[r][k] == 1) {
grid[r][k] = 2;
fresh--;
q.add(new int[] { r, k });
}
}
}
minutes++;
}
return fresh == 0 ? minutes : -1;
}
}class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
m, n, fresh, minutes = len(grid), len(grid[0]), 0, 0
q = deque()
for i in range(m):
for j in range(n):
if grid[i][j] == 2:
q.append((i, j))
elif grid[i][j] == 1:
fresh += 1
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
while q and fresh > 0:
for _ in range(len(q)):
c = q.popleft()
for d in dirs:
r, k = c[0] + d[0], c[1] + d[1]
if r >= 0 and k >= 0 and r < m and k < n and grid[r][k] == 1:
grid[r][k] = 2
fresh -= 1
q.append((r, k))
minutes += 1
return minutes if fresh == 0 else -1class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size(), fresh = 0, minutes = 0;
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});
else if (grid[i][j] == 1) fresh++;
}
int dirs[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
while (!q.empty() && fresh > 0) {
for (int s = q.size(); s > 0; s--) {
auto c = q.front();
q.pop();
for (auto& d : dirs) {
int r = c.first + d[0], k = c.second + d[1];
if (r >= 0 && k >= 0 && r < m && k < n && grid[r][k] == 1) {
grid[r][k] = 2;
fresh--;
q.push({r, k});
}
}
}
minutes++;
}
return fresh == 0 ? minutes : -1;
}
};function orangesRotting(grid) {
const m = grid.length, n = grid[0].length;
let fresh = 0, minutes = 0;
let q = [];
for (let i = 0; i < m; i++)
for (let j = 0; j < n; j++) {
if (grid[i][j] === 2) q.push([i, j]);
else if (grid[i][j] === 1) fresh++;
}
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
while (q.length > 0 && fresh > 0) {
const next = [];
for (const c of q) {
for (const d of dirs) {
const r = c[0] + d[0], k = c[1] + d[1];
if (r >= 0 && k >= 0 && r < m && k < n && grid[r][k] === 1) {
grid[r][k] = 2;
fresh--;
next.push([r, k]);
}
}
}
q = next;
minutes++;
}
return fresh === 0 ? minutes : -1;
}Edge cases to test
- No fresh oranges (answer 0)
- Fresh oranges that can never rot (-1)
- No rotten oranges but some fresh (-1)
Hints
Hint 1
All rotten oranges spread at the same time. Put all of them in the queue at the start: that is multi-source BFS.
FAQ
What is the best time complexity for Rotting Oranges?
Optimal (multi-source BFS) runs in O(m · n) time and O(m · n) extra space.
Which pattern does Rotting Oranges use?
It is a graphs problem that uses the multi source bfs pattern. Other problems with the same pattern: 01 Matrix, Pacific Atlantic Water Flow, Escape the Spreading Fire.
Is there a brute force solution for Rotting Oranges?
Yes. Simulate minute by minute takes O((m · n)²) time and O(m · n) space. Each minute, scan the grid and rot every fresh orange next to a rotten one.
Which edge cases should I test for Rotting Oranges?
No fresh oranges (answer 0); Fresh oranges that can never rot (-1); No rotten oranges but some fresh (-1).