Algorithms · Graphs & grids

Rotting Oranges

Rot spreads each minute. How long until it’s everywhere?

The problem

In a crate, 0 is empty, 1 is a fresh orange and 2 is a rotten one. Every minute, rotten oranges rot their fresh neighbours (up, down, left, right). Return how many minutes until nothing is fresh, or -1 if some orange never rots.

minutes_to_rot([[2, 1, 1], [1, 1, 0], [0, 1, 1]])4
minutes_to_rot([[2, 1, 1], [0, 1, 1], [1, 0, 1]])-1
Graphs & grids. Spread out in rings. Drop a stone in a pond: the ripple reaches everything one step away, then two steps…

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def minutes_to_rot(grid):take the crate: 0 empty, 1 fresh, 2 rotten
grid = [row[:] for row in grid]work on a copy
minutes = 0the clock starts at 0
while True:minute by minute
to_rot = []fresh oranges that rot this minute
for r in range(len(grid)):scan the whole crate, every minute
for c in range(len(grid[0])):every square
if grid[r][c] == 1:a fresh orange
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):its four neighbours
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] == 2:a rotten one?
to_rot.append((r, c))this orange will rot
breakno need to check more neighbours
if not to_rot:nothing rotted this minute
breakthe spreading has stopped
for r, c in to_rot:rot them all at once
grid[r][c] = 2now rotten
minutes += 1one more minute
fresh = any(1 in row for row in grid)any fresh oranges left?
return -1 if fresh else minutesstuck, or how long it took

Now ask: what if there were a billion?

This is how epidemics, rumours and computer viruses are modelled: “minutes” become “hops” across a network, and the same queue-of-rings tells you how fast something spreads.

Aim for O(n)🔥 boss

Think it through

Each minute, which oranges can rot something new?

  • Every rotten orange
  • Only the ones that went rotten last minute
Show the answer

Only the ones that went rotten last minute. Older rotten oranges have already rotted their neighbours. Only the newest edge of the rot matters.

So what do you keep, instead of rescanning the crate every minute?

  • A queue of newly rotten oranges, with their minute
  • A count of rotten oranges
Show the answer

A queue of newly rotten oranges, with their minute. Breadth-first search from all rotten oranges at once: the queue holds the edge, in minute order. Same idea as the Infection round.

Stuck? 3 nudges, smallest first
  1. The obvious way rescans the entire crate every single minute, even the parts where nothing is happening.
  2. Only the oranges that just went rotten can rot anything new. Keep them in a queue, with the minute they rotted.
  3. Put every rotten orange in a queue with minute 0. Pop one, rot its fresh neighbours at minute + 1, and add them to the queue.

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
from collections import dequea queue that's quick at both ends
def minutes_to_rot(grid):take the crate: 0 empty, 1 fresh, 2 rotten
grid = [row[:] for row in grid]work on a copy
queue = deque()rotten oranges whose neighbours we still need to rot
fresh = 0how many fresh oranges there are
for r in range(len(grid)):one scan to start
for c in range(len(grid[0])):every square
if grid[r][c] == 2:rotten from the start
queue.append((r, c, 0))it spreads from minute 0
elif grid[r][c] == 1:fresh
fresh += 1count it
minutes = 0the latest minute anything rotted
while queue:the rot spreads in rings
r, c, m = queue.popleft()an orange that went rotten at minute m
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):its four neighbours
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] == 1:a fresh one?
grid[nr][nc] = 2it rots…
fresh -= 1…one fewer fresh orange
minutes = m + 1…at minute m + 1
queue.append((nr, nc, m + 1))and it will spread too
return -1 if fresh else minutesstuck, or how long it took

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with graphs & grids