Show problems as
Classic problem #994MediumArrayBreadth-First SearchMatrix

Rotting Oranges

Real-world version: Rack Corruption Sweep
Tracked in this browser only
Read Rotting Oranges on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A storage aisle is wired as a rectangular grid racks. Every cell carries one of three codes:

  • 0 marks an empty bay,
  • 1 marks a node running healthy firmware,
  • 2 marks a node whose firmware is already corrupted.

Corruption travels on a fixed clock. During each tick, every healthy node that shares an edge with a node corrupted before that tick becomes corrupted itself. Empty bays carry nothing, and cells touching only at a corner are not neighbours.

Return how many ticks pass before nothing healthy is left in the aisle. If some healthy node can never be reached, return -1 instead.

Examples

Example 1

Input
racks = [[1, 1, 0], [1, 2, 1], [0, 1, 1]]
Output
2

The four edge neighbours of the corrupted middle go in tick 1, and the two remaining corner nodes go in tick 2.

Example 2

Input
racks = [[2, 0, 1]]
Output
-1

The empty bay sits between the two nodes, so the healthy one on the right is never touched.

Example 3

Input
racks = [[0, 0], [2, 0]]
Output
0

No healthy node is present when the clock starts, so the aisle is already settled.

Constraints

  • rows == racks.length
  • cols == racks[i].length
  • 1 <= rows, cols <= 10
  • Each racks[i][j] is 0, 1, or 2

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def infection_ticks(racks: list[list[int]]) -> int:
Java
public int infectionTicks(int[][] racks)