CodingNodes / Graphs / Rotting Oranges System design Space play · ←→ step · R restart

Problem

A grid holds oranges. Each cell is 0 (empty), 1 (fresh) or 2 (rotten).

Every minute, each rotten orange makes every fresh orange directly above, below, left or right of it rotten.

Return the number of minutes until no fresh orange is left, or -1 if some fresh orange can never rot.

Constraints

  • 1 ≤ rows, cols ≤ 10
  • grid[r][c] is 0, 1 or 2

Examples: pick one to animate

Solutions

TimeO(rows · cols) SpaceO(rows · cols)

Time: Every cell is scanned once, and every orange enters the queue at most once and checks 4 neighbors.

Space: In the worst case (a grid full of oranges) the queue holds O(rows · cols) cells.

Put every rotten orange in the queue first, then process the queue one level at a time. Each level is one minute. Track the fresh count so the end condition and the -1 case are O(1).