DSA AnimatorDSA animations
Rotting Oranges LC #994 Medium Graph · Multi-Source BFS
Problem

Given an m×n grid: 0=empty, 1=fresh, 2=rotten. Every minute, fresh oranges 4-adjacent to rotten become rotten. Return minimum minutes until no fresh remains, or -1 if impossible.

Example
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Try Examples
Custom: rows separated by / (0=empty 1=fresh 2=rotten)
Approach
Multi-Source BFS
Enqueue ALL rotten oranges initially. Each BFS level = 1 minute. Spread rot to fresh neighbors. Return minutes if fresh==0, else -1.
Grid — 0=empty 1=fresh 2=rotten
Load an example to begin.
Variables
Minute
—
Fresh
—
Queue
—
New rot
—
Step Logic
Press ▶ Play or Next Step to begin.
✓
Ready
0 / 0
Select an example and press Play.
Algorithm
1
Count fresh, enqueue all rotten
2
BFS: each level = 1 minute, rot spreads to neighbors
3
Return minutes if fresh==0, else -1
Time
O(m·n)
Space
O(m·n)
Why Multi-Source BFS

All rotten oranges start simultaneously. Each BFS level = 1 minute. Fresh neighbors become rotten when visited. If fresh>0 after BFS ends, some oranges are unreachable → return -1.

How to solve Rotting Oranges

LeetCode 994 · Medium · Graph · Pattern: Multi-Source BFS

Why the obvious approach is slow

You could rescan the whole grid every minute, looking for oranges next to rotten ones. That repeats a lot of work, up to O of rows times columns per minute.

The key idea

All rotten oranges start spreading at the same time. So put every rotten orange into the queue at the start, which is a multi source BFS. Process the queue one level at a time, and each level is one minute. Count the fresh oranges first, and decrease the count whenever one rots. If fresh oranges remain at the end, some were unreachable, so return −1.

Remember

Many starting points at once means multi source BFS. One BFS level equals one unit of time.

Run the animation above on your own input, or watch the 1:60 video explanation of Rotting Oranges with a dry run and Java code.

More Graph problems