Back to Practice
#0268
Rotting Oranges
MediumDSA28 min20 XP
Problem
Grid values are 0 empty, 1 fresh orange, and 2 rotten orange. Each minute, rotten oranges rot adjacent fresh oranges. Return minutes until all are rotten, or -1 if impossible.
Why This Matters
This is the cleanest example of BFS starting from many sources at once.
Function Signature
def oranges_rotting(grid):
Examples
Example 1
Inputgrid = [[2,1,1],[1,1,0],[0,1,1]]
Output4
The rot spreads layer by layer and reaches the final orange after 4 minutes.
Constraints
- Return the exact requested value.
- Handle edge cases cleanly.
- Use the intended DSA pattern when brute force would scale poorly.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
All eventually rot
Input[[2,1,1],[1,1,0],[0,1,1]]
Expected4
Four BFS layers are needed.
Unreachable fresh orange
Input[[2,1,1],[0,1,1],[1,0,1]]
Expected-1
Some fresh oranges are isolated from all rotten sources.
Hidden Test Categories
no fresh orangesno rotten orangesone-cell grid