Rotting Oranges

35 min · orangesRotting()

One spoiled orange can ruin a crate, but only if the rot can physically reach the rest. The clock makes that reach measurable.

You're given a rectangular grid whose cells mean:

  • 0: empty space,
  • 1: a fresh orange, and
  • 2: a rotten orange.

During each minute, every rotten orange spreads rot to any fresh orange directly above, below, left, or right of it. All spreading within a minute happens at the same time.

Return the number of minutes needed to leave no fresh orange behind. Return -1 when at least one fresh orange can never be reached. If the grid starts with no fresh oranges, return 0.

Constraints

  • 1 <= grid.length <= 100
  • 1 <= grid[i].length <= 100
  • Every row has the same length.
  • Every cell is 0, 1, or 2.

Hints

Start with the clock

You can copy the grid, scan every cell, mark the fresh neighbors of rotten cells, and repeat until a scan changes nothing. What work gets repeated each minute?

Many starting points, one wave

Every orange that is rotten at minute 0 belongs in the same initial queue. Process that whole layer before increasing the minute count.

Count what remains

Track the number of fresh oranges. Each orange enters the queue only when it first rots, and the final count tells you whether an isolated pocket survived.

Follow-up

How would you return a second grid containing the exact minute when each reachable orange rots, while keeping the same time complexity?

Visible cases

Examples

Example 1

ready
Input
grid = [
  [
    2,
    1,
    1
  ],
  [
    1,
    1,
    0
  ],
  [
    0,
    1,
    1
  ]
]
Expected
4
Why
the rot reaches the final orange after four synchronized waves

Example 2

ready
Input
grid = [
  [
    2,
    1,
    1
  ],
  [
    0,
    1,
    1
  ],
  [
    1,
    0,
    1
  ]
]
Expected
-1
Why
the fresh orange in the lower-left corner is cut off by empty cells

Example 3

ready
Input
grid = [
  [
    0,
    2
  ]
]
Expected
0
Why
there are no fresh oranges at the start

Interview signal

Asked at

AmazonGoogleMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite