Breadth-First Search
Medium
Rotting Oranges
Determine the minimum time required to rot all oranges.
20 min
Solve on LeetCodeProblem Understanding
You have a grid with:
0: Empty cell1: Fresh orange2: Rotten orange
Every minute, a rotten orange infects its 4-directionally adjacent fresh neighbors. Return minimum minutes until no fresh orange remains. If impossible, return -1.
Algorithm Strategy
This simulates a process expanding over time, which is classic BFS.
- Multi-source: Start with ALL initially rotten oranges in the Queue.
- Count Fresh: Count total fresh oranges initially. If 0, return 0.
- Level-by-Level: Process the queue layer by layer (minutes). Each layer spreads rot to neighbors.
- Decrement
fresh_countwhenever a fresh orange rots.
- Decrement
- Completion: If queue empty and
fresh_count == 0, return time. Else return -1.
Interactive Visualization
Step 1 / 1
Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Solution Code
- Complexity Analysis
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
