Firebreak Choice in a Spreading Crop Disease Grid
Arrays & HashingAuto-graded · 19 test casesLast updated
Simulate a synchronous grid disease model with delayed death or recovery, then try every single-row or single-column firebreak to minimize dead plants.
A field is an R x C grid of plants. Each plant starts in one of four conditions, given as lowercase strings: "healthy", "infected", "recovered" or "dead". Two plants are neighbors if they share an edge, so each plant has at most four neighbors.
Daily rules
The simulation runs for days days, numbered 1, 2, .... On each day, every plant that is not dead and not already waiting on an outcome (see below) is examined. Let m be the number of its neighbors that are currently infected, using the grid as it was at the start of that day.
- If
m >= high, the plant is doomed: it will become dead. - Otherwise, if
m >= low, the plant is recovering: it will become recovered. - Otherwise, nothing happens to it.
A doomed or recovering plant is waiting. It is treated as infected for neighbor counts the whole time it waits. It is not examined again until its outcome is applied.
Timing of the outcome
A plant that starts waiting on day d has its outcome applied at the end of day d + delay - 1. For delay = 1, the outcome is applied at the end of day d itself, so the plant never appears as waiting at the start of a later day. For delay = 2, the plant waits through day d + 1 and changes at the end of that day. Outcomes that would land after day days are never applied, so those plants are not dead.
Simultaneity
All decisions on a day use only the snapshot from the start of that day. All changes for that day (new waiting plants and applied outcomes) are written together at the end of the day.
Other details
- Dead plants never change and never count as infected.
- Plants that are
"infected"at the start and not waiting are examined like any other non-dead plant. They can start waiting on any day. - Recovered plants are examined too, so they can become infected again and start waiting.
- A plant is counted as infected if it is in the
"infected"condition or is waiting. Healthy and recovered plants are not infected. - With
low = 0, every examined plant starts waiting on every day it is examined. Apply the rules literally.
Firebreak choice
Before day 1, you must burn exactly one whole row or exactly one whole column. Every plant on that line immediately becomes dead, even if it was already dead.
Try all R + C options. For each, simulate days days and count the dead plants in the final grid, including the burned ones and plants that were dead from the start. Return the smallest count together with the line that achieves it.
Tie-break: Check rows in increasing index order, then columns in increasing index order. Report the first option that reaches the minimum, so a later option replaces it only if strictly smaller.
Function
Return a list [min_dead, [kind, index]], where kind is the string "row" or "column" and index is the 0-based index of the burned line.
Constraints
1 <= R, C, and the grid is rectangular.0 <= low <= highdelay >= 1days >= 0- Every cell is one of
"healthy","infected","recovered","dead". daysmay be large relative to the grid, so stopping early once the grid stops changing is worthwhile.
Examples
Example 1
Input: min_dead_after_burn([['infected', 'healthy', 'healthy'], ['healthy', 'healthy', 'healthy']], 1, 3, 1, 2)
Output: [2, ['column', 0]]
Example 2
Input: min_dead_after_burn([['healthy', 'healthy', 'healthy'], ['healthy', 'infected', 'healthy'], ['healthy', 'healthy', 'healthy']], 1, 4, 2, 3)
Output: [3, ['row', 0]]
Example 3
Input: min_dead_after_burn([['infected', 'healthy', 'recovered', 'infected']], 1, 2, 3, 5)
Output: [1, ['column', 0]]
Hints
Hint 1
Write a function that simulates one fixed starting grid for `days` days and returns the dead count, then call it once for every row and every column.
Hint 2
Keep a numeric state per cell plus a separate waiting counter, and build brand-new arrays each day so every decision sees only the start-of-day snapshot. Waiting plants must count as infected.
Hint 3
Work out the timing on paper: with `delay = 1` the outcome is applied the same day, so a waiting plant is stored with counter `delay - 1`. If a full day leaves both the state and the counters unchanged, the simulation has reached a fixed point and you can stop.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem has two layers.
- Simulation of one scenario. The grid evolves synchronously, so each day we build fresh arrays from a snapshot of the previous day. Each cell has a state (healthy, infected, recovered, dead, doomed, recovering) and a counter for how much longer it must wait.
- Search over firebreaks. There are only
R + Clegal burn choices. We simulate each one from the same starting grid and keep the best.
One simulated day
For every non-dead cell:
- Waiting cell (doomed or recovering). If its counter is at most 1, apply the outcome (dead or recovered). Otherwise decrement the counter. Waiting cells are never re-examined.
- Any other cell. Count infected neighbors from the snapshot, where "infected" means infected, doomed or recovering.
- If the count is at least
high, the cell becomes doomed. - Otherwise, if the count is at least
low, it becomes recovering. - Otherwise it is unchanged.
- When a cell starts waiting, store the counter as
delay - 1. Ifdelay == 1, apply the outcome immediately, at the end of that same day.
- If the count is at least
This produces the required timing: a plant that starts waiting on day d changes at the end of day d + delay - 1.
If a day leaves both the state grid and the counter grid unchanged, the next day sees the same snapshot and makes the same decisions, so nothing will ever change again. We can stop early, which handles large days.
Why it is correct
- Neighbor counts and all decisions use only the start-of-day arrays, and all writes go to new arrays. This gives the required simultaneity.
- Waiting cells stay in a state that counts as infected until the outcome is applied, and they skip re-examination.
- The search covers every legal action, each simulated faithfully from the same initial grid. Taking the first strict minimum in the order rows then columns gives the specified tie-break.
Greedy shortcuts are unsafe here. A burn adds dead cells immediately, but it may cut off a spread that would kill many more. Only the full dynamics decide.
Complexity
Let S <= days be the number of days actually simulated, which is often much smaller because of early stopping.
- One simulation:
O(S * R * C)time andO(R * C)space. - All options:
O((R + C) * S * R * C)time. Space staysO(R * C)because simulations run one at a time.
Reference solution
from typing import List
def min_dead_after_burn(grid: List[List[str]], low: int, high: int, delay: int, days: int) -> List:
HEALTHY, INFECTED, RECOVERED, DEAD = 0, 1, 2, 3
DOOMED, RECOVERING = 4, 5
codes = {"healthy": HEALTHY, "infected": INFECTED,
"recovered": RECOVERED, "dead": DEAD}
rows = len(grid)
cols = len(grid[0])
def simulate(kind, index):
state = [[codes[v] for v in row] for row in grid]
if kind == "row":
for c in range(cols):
state[index][c] = DEAD
else:
for r in range(rows):
state[r][index] = DEAD
wait = [[0] * cols for _ in range(rows)]
for _ in range(days):
nxt = [row[:] for row in state]
nwait = [row[:] for row in wait]
for r in range(rows):
for c in range(cols):
cur = state[r][c]
if cur == DEAD:
continue
if cur == DOOMED or cur == RECOVERING:
if wait[r][c] <= 1:
nxt[r][c] = DEAD if cur == DOOMED else RECOVERED
nwait[r][c] = 0
else:
nwait[r][c] = wait[r][c] - 1
continue
m = 0
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 state[nr][nc] in (INFECTED, DOOMED, RECOVERING):
m += 1
if m >= high:
wait_state, final_state = DOOMED, DEAD
elif m >= low:
wait_state, final_state = RECOVERING, RECOVERED
else:
continue
if delay <= 1:
nxt[r][c] = final_state
nwait[r][c] = 0
else:
nxt[r][c] = wait_state
nwait[r][c] = delay - 1
if nxt == state and nwait == wait:
break
state, wait = nxt, nwait
return sum(v == DEAD for row in state for v in row)
options = [("row", r) for r in range(rows)] + [("column", c) for c in range(cols)]
best_count = None
best_action = None
for kind, index in options:
dead = simulate(kind, index)
if best_count is None or dead < best_count:
best_count = dead
best_action = [kind, index]
return [best_count, best_action]