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 - BFS Solution INPUT Initial Grid (m x n) 2 1 1 1 1 0 0 1 1 2 = Rotten 1 = Fresh 0 = Empty grid = [[2,1,1], [1,1,0], [0,1,1]] ALGORITHM STEPS 1 Initialize BFS Queue Add all rotten oranges (2s) Count fresh oranges 2 Process Each Level Dequeue rotten orange Check 4 directions 3 Rot Adjacent Fresh Mark fresh as rotten Add to queue, decrement count 4 Track Minutes Increment time after level Return -1 if fresh remain Time Progression: t=0 t=1 t=2 t=3 t=4 Spread: 1 --> 2 --> 2 --> 1 cells Queue: FIFO level-by-level FINAL RESULT Final Grid (All Rotten) 2 2 2 2 2 0 0 2 2 OUTPUT 4 OK - All oranges rotted Fresh count = 0 Minutes elapsed = 4 Key Insight: BFS naturally processes nodes level by level, making it perfect for tracking time/distance. Each BFS level = 1 minute. Start queue with ALL rotten oranges (multi-source BFS). Time Complexity: O(m*n) | Space Complexity: O(m*n) for the queue in worst case. TutorialsPoint - Rotting Oranges | BFS (Breadth-First Search)
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