QuestionsDSA

Rotting Oranges

BFS (Breadth-First)MediumDSA

In a grid, 2 = rotten orange, 1 = fresh, 0 = empty. Each minute, rotten oranges rot 4-directional fresh neighbors. Return minutes until none are fresh, or -1 if impossible.

What it tests

Multi-source BFS — start from ALL rotten cells at once — and counting 'time' as BFS levels.

Approach & answer

Seed the queue with every rotten orange (multi-source BFS). BFS outward one minute per level, rotting fresh neighbors and enqueuing them. The number of levels processed is the elapsed time. If any fresh orange remains after the queue drains, it was unreachable — return -1. The key insight: single-source BFS finds the shortest distance from one origin, but here rot spreads from many origins at once, so you push all sources onto the queue up front and let them expand in lockstep. Track the count of fresh oranges and decrement as you rot them, so the final reachability check is O(1). Time = distance from the nearest source, which is exactly what BFS computes level by level.

Use this technique when

'Time to spread', 'shortest distance from any of several sources' → multi-source BFS.

Complexity

Time O(rows·cols) · Space O(rows·cols)

References

js