Rotting Oranges - Problem

You are given an m x n grid where each cell can have one of three values:

  • 0 representing an empty cell
  • 1 representing a fresh orange
  • 2 representing 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
Rotting Oranges: Spread SimulationInput Grid211110011Spreading Process4 minutes222220022Result4 minutesAll fresh orangesbecame rottenLegend:Rotten Orange (2)Fresh Orange (1)Empty Cell (0)Rot spreads 4-directionally (up, down, left, right) each minute
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
Asked in
Amazon 42 Microsoft 28 Google 24 Bloomberg 18
286.2K Views
High Frequency
~15 min Avg. Time
8.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen