Rotting Oranges
Find the minutes until the whole field burns
DSA, Medium, Graphs
Which structure or algorithm, and what does it cost.
This is the rotting oranges problem, told as a grass fire. A field is a grid of whole numbers. 0 is bare ground, 1 is unburnt grass and 2 is burning grass. Each minute, every unburnt grass cell that shares a side with a burning cell starts to burn. Burning cells keep burning. Write minutes_to_burn(field). It returns the number of minutes until no unburnt grass is left. If some grass can never catch fire, return -1. If there is no grass at the start, return 0.
Examples
Constraints
- 1 <= rows <= 120 and 1 <= columns <= 120.
- Every cell is 0, 1 or 2.
- All rows have the same length.
Your answer must contain
- Why all fires start together; the method; code; time and memory cost; a hand trace of example 1; the answers 0 and -1.
Target Aim for O(R * C) time and memory, where R is the number of rows and C the number of columns.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Fire spreads from every burning cell at the same moment. Why would searching from one burning cell at a time give the wrong time?
Hint 2 the approach
Think in minutes. In each minute, the cells that are burning now light their grass neighbours. Remember which cells caught fire most recently.
Hint 3 the key step
Queue every burning cell first and count the grass. Go through the queue one minute at a time. Stop at zero grass, or answer -1 if the queue runs dry.
Walkthrough
Full walkthrough brute force to best
Brute force
Simulate the minutes. In each minute, scan the whole field and find every grass cell next to a burning cell, then light them all together. Repeat until a minute changes nothing. One scan costs O(R * C), and a winding path of grass can need about R * C minutes, so this costs O((R * C)^2) time.
Best method
Spread the fire in rounds with a queue. Put every burning cell in the queue first and count the unburnt grass cells. Then repeat: if the queue is empty or no grass is left, stop. Otherwise add one minute and take exactly the cells that were in the queue when the minute began. For each one, look at its four side neighbours. If a neighbour is unburnt grass, light it, lower the grass count and queue it. Starting with all fires at once is what makes the minute count right, because fire spreads from all of them together. At the end, the answer is the minute count if no grass is left, and -1 if some grass was never reached.
Hand trace
Example 1: the fires are (0,0) and (2,3), and there are 7 grass cells. Minute 1: (0,0) lights (0,1), and (2,3) lights (1,3) and (2,2), so 4 grass cells are left. Minute 2: (0,1) lights (0,2) and (1,1), and (2,2) lights (2,1), so 1 grass cell is left. Minute 3: (2,1) lights (2,0), so no grass is left. The answer is 3.
Code
from collections import deque
def minutes_to_burn(field):
rows, cols = len(field), len(field[0])
todo = deque()
grass = 0
for r in range(rows):
for c in range(cols):
if field[r][c] == 2:
todo.append((r, c))
elif field[r][c] == 1:
grass += 1
lit = set()
minutes = 0
while todo and grass:
minutes += 1
for _ in range(len(todo)): # only the cells burning at the start of this minute
r, c = todo.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and field[nr][nc] == 1 and (nr, nc) not in lit:
lit.add((nr, nc))
grass -= 1
todo.append((nr, nc))
return minutes if grass == 0 else -1Time and memory
O(R * C) time and O(R * C) memory. Each cell is lit and queued at most once and looked at from four sides. The queue and the set of lit cells hold up to R * C cells.
Common mistakes
- Running a search from one burning cell, then another. Fire spreads from all burning cells at the same time, so start with all of them in the queue.
- Lowering the grass count when you take a cell off the queue instead of when you light it. Two neighbours can light the same cell, and it is counted twice.
- Returning the minute count when grass is left. If some grass was never reached, the answer is -1.