Grid as an Implicit Graph

Rotting Oranges

Medium
Solve it on LeetCode ↗

The problem

In a grid of empty cells (0), fresh oranges (1), and rotten oranges (2), every minute fresh oranges adjacent to rotten ones rot. Return the minutes until no fresh orange remains, or −1 if impossible.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Scan the grid once: enqueue all rotten cells, count fresh ones.
  2. 2BFS level by level; each level = one minute. Rot every fresh neighbor, decrement the fresh counter, enqueue it.
  3. 3Track the depth of the last processed level.
  4. 4If fresh count reaches 0, return the elapsed minutes; otherwise −1.

Key insight

Seeding BFS with MANY sources at distance 0 computes each cell’s distance to its NEAREST rotten orange — simultaneous spread falls out for free.

The solution

Watch out for

  • Guard the loop with "fresh > 0" or you over-count a final minute where nothing rots.
  • A grid with zero fresh oranges must return 0, not −1 — the guard handles that too.