Algo-Sim › Grid Graphs
Rotting Oranges
Medium · Grid Graphs · step through it in Java, Python and C++ on your own input
Each minute, rotten oranges rot their fresh neighbours. How many minutes until none is fresh? Return -1 if some never rot.
Problem
Each cell is empty (0), a fresh orange (1) or a rotten one (2). Every minute, each rotten orange rots the fresh oranges directly above, below, left and right of it. Return how many minutes pass until no fresh orange is left, or -1 if some can never rot.
Constraints
- 1 ≤ m, n ≤ 10
- grid[i][j] is 0, 1 or 2
- All rotten oranges spread at the same time: one BFS from all of them
Edge cases to test
- No fresh oranges:
0 - A fresh orange that can never rot:
-1 - No rotten oranges but some fresh:
-1
Follow-up questions
- Why one BFS from all rotten oranges at once?
- Starting every source at minute 0 gives each cell its distance to the nearest source in one O(mn) pass.
- How do you know when to stop?
- Count fresh oranges up front and decrement as they rot; stop when it reaches 0.
Solution
Java
public int orangesRotting(int[][] grid) {
int rows = grid.length, cols = grid[0].length, fresh = 0, minutes = 0;
int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
Queue<int[]> queue = new ArrayDeque<>();
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 2) queue.offer(new int[] { r, c });
else if (grid[r][c] == 1) fresh++;
}
}
while (!queue.isEmpty() && fresh > 0) {
minutes++;
for (int size = queue.size(); size > 0; size--) {
int[] cell = queue.poll();
for (int[] d : dirs) {
int nr = cell[0] + d[0], nc = cell[1] + d[1];
if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] != 1) continue;
grid[nr][nc] = 2;
fresh--;
queue.offer(new int[] { nr, nc });
}
}
}
return fresh == 0 ? minutes : -1;
}Python
from collections import deque
def oranges_rotting(grid):
rows, cols, fresh, minutes = len(grid), len(grid[0]), 0, 0
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
queue = deque()
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
queue.append((r, c))
elif grid[r][c] == 1:
fresh += 1
while queue and fresh > 0:
minutes += 1
for _ in range(len(queue)):
cr, cc = queue.popleft()
for dr, dc in dirs:
nr, nc = cr + dr, cc + dc
if not (0 <= nr < rows and 0 <= nc < cols) or grid[nr][nc] != 1:
continue
grid[nr][nc] = 2
fresh -= 1
queue.append((nr, nc))
return minutes if fresh == 0 else -1C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int orangesRotting(vector<vector<int>> &grid) {
int rows = int(grid.size()), cols = int(grid[0].size()), fresh = 0, minutes = 0;
vector<vector<int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
deque<vector<int>> queue = {};
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 2)
queue.push_back(vector<int>{r, c});
else if (grid[r][c] == 1)
fresh++;
}
}
while (!queue.empty() && fresh > 0) {
minutes++;
for (int size = int(queue.size()); size > 0; size--) {
vector<int> cell = queue.front();
queue.pop_front();
for (vector<int> &d : dirs) {
int nr = cell[0] + d[0], nc = cell[1] + d[1];
if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] != 1)
continue;
grid[nr][nc] = 2;
fresh--;
queue.push_back(vector<int>{nr, nc});
}
}
}
return fresh == 0 ? minutes : -1;
}
};
More Grid Graphs problems
- Flood Fill (Easy)
- Number of Islands (BFS) (Medium)
- Number of Islands (DFS) (Medium)
- Max Area of Island (Medium)
- 01 Matrix (Medium)
- Walls and Gates (Medium)
- Shortest Path in Binary Matrix (Medium)
- Shortest Bridge (Medium)
- Shortest Path in a Grid with Obstacles Elimination (Hard)
- Surrounded Regions (Medium)
- Pacific Atlantic Water Flow (Medium)
- Path With Minimum Effort (Medium)
- Minimum Cost to Make at Least One Valid Path in a Grid (Hard)
- Swim in Rising Water (Hard)