BFS

994. Rotting Oranges · multi-source BFS

← all LeetCode ↗

How many minutes until everything rots?

Each minute, every rotten orange (2) rots its fresh (1) neighbours. Empty cells (0) are gaps. Return the minutes until no fresh orange remains, or -1 if some can never rot.

The BFS idea → This is BFS with many starting points at once. Put all rotten oranges into the queue at minute 0. Then BFS outward: everything you reach on the next wave rots at minute+1. Because BFS explores level by level, the wave number is the elapsed time. The answer is the last minute anything rots.

Grid (number = minute it rotted)

fresh (1) rotten (2) empty (0) rotting this wave

What's happening

Queue (FIFO →) cell · minute

Counters

Code

Complexity: O(rows × cols) time and space. Every orange is enqueued once. · Key trick: seed the queue with all sources before the loop — same pattern as 01 Matrix (542), Walls and Gates (286), Map of Highest Peak (1765).