← Back to DSA Animator
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.