Grid Infection Spread with Time Limit
Trees & GraphsAuto-graded · 24 test casesLast updated
Tests BFS-based grid simulation with simultaneous state updates, barrier cells, and handling extremely large iteration counts efficiently.
You are given a rectangular grid representing a forest. Each cell contains one of three characters:
'R'represents an infected tree'H'represents a healthy tree'-'represents bare ground (no tree)
Each time step, infection spreads simultaneously: every healthy tree that is directly adjacent (up, down, left, or right) to at least one infected tree becomes infected. Diagonal neighbors do not count. Bare ground never becomes infected and does not transmit infection.
Trees that become infected during a particular time step do not spread infection until the next time step.
Given the initial grid state and a number of time steps, return the grid state after that many time steps have elapsed.
Constraints
1 <= len(grid) <= 2001 <= len(grid[0]) <= 200- All rows have equal length
- Each cell is
'R','H', or'-' 0 <= steps <= 10^9
Examples
Example 1
Input: grid_after_infection(['RH-', 'HHH', '-HH'], 1)
Output: ['RR-', 'RHH', '-HH']
Example 2
Input: grid_after_infection(['RH-', 'HHH', '-HH'], 3)
Output: ['RR-', 'RRR', '-RH']
Example 3
Input: grid_after_infection(['H-R'], 5)
Output: ['H-R']
Hints
Hint 1
A naive loop simulating each time step individually will be too slow when steps is very large. What determines when the grid stops changing?
Hint 2
This is a multi-source breadth-first search problem where distance represents time steps. Each BFS level corresponds to one time step.
Hint 3
Process the BFS queue one complete level at a time to ensure trees infected in step N only spread infection in step N+1, not step N.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The challenge is handling extremely large values of steps (up to 10^9). Simulating each step naively by scanning the entire grid would require O(rows × cols × steps) time, which is prohibitively expensive.
The key insight is that infection spreads like a wave front: only newly infected trees matter for the next step. Trees infected earlier have already spread to all their neighbors. This naturally suggests breadth-first search (BFS), where:
- All initially infected trees form the starting frontier (level 0)
- Each BFS level represents one time step
- The infection cannot spread beyond rows × cols steps at most, since each tree infects at most once
We use multi-source BFS starting from all infected cells simultaneously:
- Initialize a queue with all initially infected positions
- For each time step, process exactly the cells that were in the queue at the start of that step (one complete BFS level)
- For each cell processed, check its four orthogonal neighbors
- If a neighbor is healthy (
'H'), mark it infected and add it to the queue - Stop after
stepsiterations or when the queue empties (no more spread possible)
Processing one complete level at a time ensures simultaneity: trees that become infected during step N are added to the queue but not processed until step N+1, matching the requirement that newly infected trees don't spread until the next step.
Marking cells as infected immediately when enqueueing them prevents duplicate processing and correctly blocks further spread through those positions.
Complexity
Time: O(rows × cols). Each cell is enqueued and processed at most once, regardless of the value of steps. This makes the solution efficient even when steps = 10^9.
Space: O(rows × cols) for the mutable grid copy and the queue.
Solution
from collections import deque
from typing import List
def grid_after_infection(grid: List[str], steps: int) -> List[str]:
rows = len(grid)
cols = len(grid[0])
state = [list(row) for row in grid]
queue = deque()
for r in range(rows):
for c in range(cols):
if state[r][c] == "R":
queue.append((r, c))
elapsed = 0
while queue and elapsed < steps:
elapsed += 1
level_size = len(queue)
for _ in range(level_size):
r, c = queue.popleft()
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and state[nr][nc] == "H":
state[nr][nc] = "R"
queue.append((nr, nc))
return ["".join(row) for row in state]