Breadth-First Search
Medium

Rotting Oranges

Determine the minimum time required to rot all oranges.
Problem Understanding

You have a grid with:

  • 0: Empty cell
  • 1: Fresh orange
  • 2: 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.

  1. Multi-source: Start with ALL initially rotten oranges in the Queue.
  2. Count Fresh: Count total fresh oranges initially. If 0, return 0.
  3. Level-by-Level: Process the queue layer by layer (minutes). Each layer spreads rot to neighbors.
    • Decrement fresh_count whenever a fresh orange rots.
  4. 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.
Unlock VisualizerPREMIUM FEATURE

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.

Start Your Premium Prep