Rotting Oranges - Problem
You are given an m x n grid where each cell can have one of three values:
0representing an empty cell1representing a fresh orange2representing a rotten orange
Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.
Input & Output
Example 1 — Standard Grid
$
Input:
grid = [[2,1,1],[1,1,0],[0,1,1]]
›
Output:
4
💡 Note:
Initially one rotten orange at (0,0). After 1 minute: (0,1) and (1,0) rot. After 2 minutes: (0,2), (1,1) rot. After 3 minutes: (2,1) rots. After 4 minutes: (2,2) rots. All fresh oranges are now rotten.
Example 2 — Impossible Case
$
Input:
grid = [[2,1,1],[0,1,1],[1,0,1]]
›
Output:
-1
💡 Note:
The fresh orange at (2,0) is isolated by empty cells and cannot be reached by the spreading rot from (0,0). Some fresh oranges will remain forever fresh.
Example 3 — No Fresh Oranges
$
Input:
grid = [[0,2]]
›
Output:
0
💡 Note:
There are no fresh oranges to rot, so 0 minutes are needed.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 10
- grid[i][j] is 0, 1, or 2
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
3×3 grid with fresh (1), rotten (2), and empty (0) cells
2
Spreading Process
Rot spreads to 4-directionally adjacent fresh oranges each minute
3
Result
Return total minutes needed or -1 if impossible
Key Takeaway
🎯 Key Insight: Use multi-source BFS to simulate simultaneous spreading from all rotten oranges
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code