Grid Contagion Simulation
Trees & GraphsAuto-graded · 25 test casesLast updated
Simulate multi-source BFS propagation across a 2D grid up to a maximum number of steps.
You are given a 2D matrix representing a grid of cells. Each cell contains one of three integers:
0: an empty space,1: an uninfected cell,2: an infected cell.
Infection spreads synchronously in rounds. During each round, any uninfected cell (1) that shares an edge (up, down, left, or right) with a cell that was already infected (2) at the start of that round becomes infected.
Given the initial grid state and an integer days representing the total number of rounds, return the state of the grid after exactly days rounds have elapsed.
Note:
- Empty spaces (
0) cannot be infected and block the spread of infection. - Cells infected during a round cannot spread the infection until the next round.
- Once infected, a cell remains infected permanently.
- If
days == 0, the grid remains in its initial state. - The function should return a new grid and avoid mutating the original input matrix.
Constraints
m == len(grid)n == len(grid[i])1 <= m, n <= 300grid[r][c]is0,1, or2.0 <= days <= 10^9
Examples
Example 1
Input: grid_after_days([[2, 1, 1, 1], [1, 1, 0, 1], [0, 1, 1, 2]], 1)
Output: [[2, 2, 1, 1], [2, 1, 0, 2], [0, 1, 2, 2]]
Example 2
Input: grid_after_days([[2, 1, 1, 1], [1, 1, 0, 1], [0, 1, 1, 2]], 3)
Output: [[2, 2, 2, 2], [2, 2, 0, 2], [0, 2, 2, 2]]
Example 3
Input: grid_after_days([[2, 0, 1], [0, 1, 1]], 5)
Output: [[2, 0, 1], [0, 1, 1]]
Hints
Hint 1
Think of the propagation as a multi-source Breadth-First Search (BFS) where all initial infected cells start at distance 0.
Hint 2
Instead of simulating day-by-day up to 10^9 times, notice that the grid can only change at most O(m * n) times before stopping.
Hint 3
Process the BFS level by level, decrementing or counting steps, and stop early if no new cells become infected.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem can be modeled as a multi-source Breadth-First Search (BFS) on a grid:
- Initial State (Level 0): Find all cells that are initially infected (
2). These form our starting frontier. - Synchronous Propagation: In each day (or step), iterate through the current frontier of infected cells. For every adjacent cell (up, down, left, right) that contains an uninfected value (
1), mark it as infected (2) and add it to the next frontier level. - Termination: Stop propagating when either
dayssteps have been performed or the frontier becomes empty (meaning no new cells can be infected).
Using level-by-level BFS ensures that cells infected during round $d$ do not infect their neighbors until round $d + 1$. Furthermore, terminating early when the frontier is empty handles cases where days is arbitrarily large (up to $10^9$) without redundant computations.
Complexity
- Time Complexity: $\mathcal{O}(m \cdot n)$. Every cell is pushed into the queue at most once and has a constant number of neighbors (4). The maximum number of levels executed is bounded by $m \cdot n$, even if
daysis up to $10^9$. - Space Complexity: $\mathcal{O}(m \cdot n)$ to store the copy of the output grid and the BFS frontier queue.
Python Reference Solution
from typing import List
def grid_after_days(grid: List[List[int]], days: int) -> List[List[int]]:
m = len(grid)
n = len(grid[0])
res = [row[:] for row in grid]
frontier = [(r, c) for r in range(m) for c in range(n) if grid[r][c] == 2]
elapsed = 0
while frontier and elapsed < days:
elapsed += 1
nxt = []
for r, c in frontier:
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n and res[nr][nc] == 1:
res[nr][nc] = 2
nxt.append((nr, nc))
frontier = nxt
return res