Rotting Oranges
Master this topic with zero to advance depth.
Rotting Oranges
You are given an m x n grid where each cell can have one of three values:
0representing an empty cell,1representing a fresh orange, or2representing 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.
Visual Representation
Minute 0: [[2,1,1],[1,1,0],[0,1,1]]
Minute 1: [[2,2,1],[2,1,0],[0,1,1]]
Minute 2: [[2,2,2],[2,2,0],[0,1,1]]
Minute 3: [[2,2,2],[2,2,0],[0,2,1]]
Minute 4: [[2,2,2],[2,2,0],[0,2,2]]
Result: 4Examples
Fresh oranges at (0,1), (0,2), (1,0), (1,1), (2,1), (2,2) rot in 4 minutes.
Level I: Brute Force (Simulation)
Intuition
Simulate the rotting process minute by minute. In each minute, look for fresh oranges that are adjacent to any rotten orange. Mark them to rot in the next minute. Repeat this until no new oranges rot.
Thought Process
- In a loop:
- Check every cell. If it's fresh ('1') and has a rotten neighbor ('2'), mark it to rot.
- Update the grid. Increment time.
- If no orange rotted in this round, stop.
- After the loop, check if any fresh oranges remain.
Why it's inefficient
We iterate through the entire grid multiple times (up to times).
Detailed Dry Run
Grid: [[2,1,1],[0,1,1],[1,0,1]] Min 1: (0,0) rots (0,1). Grid: [[2,2,1],...] Min 2: (0,1) rots (0,2). Grid: [[2,2,2],...] ...
Level III: Optimal (Multi-source BFS)
Intuition
Rotting spreads like a wave. BFS is perfect for level-by-level spreading. Instead of one source, we start with all initial rotten oranges in the queue.
Thought Process
- Count
freshoranges and add all rotten orange coordinates to a Queue. - While queue is not empty and
fresh > 0:- For all oranges currently in the queue (this level/minute):
- Poll an orange, visit its 4 neighbors.
- If neighbor is fresh:
- Mark it rotten, decrement
fresh, add to queue.
- Mark it rotten, decrement
- Increment
minutesafter processing each level.
- For all oranges currently in the queue (this level/minute):
- Return
minutesiffresh == 0, else-1.
Pattern: Multi-source BFS
Detailed Dry Run
Grid: [[2,1,1],[1,1,0],[0,1,1]]
- Queue: [(0,0)], Fresh: 6
- Min 1: Rot (0,1), (1,0). Queue: [(0,1),(1,0)], Fresh: 4
- Min 2: Rot (0,2), (1,1). Queue: [(0,2),(1,1)], Fresh: 2 ...
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.