Virus Spread Simulation with Recovery and Infection Thresholds
Trees & GraphsAuto-graded · 22 test casesLast updated
Models discrete-time epidemic propagation on a grid where cells require multiple infected neighbors to catch the virus and recover after a fixed duration.
Virus Spread Simulation with Recovery and Infection Thresholds
You need to simulate how a contagious virus spreads across a rectangular grid of cells arranged in m rows and n columns. Each cell starts in one of these states:
0: Healthy and vulnerable to infection1: Currently infected (patient zero locations at timet = 0)-1: Blocked cell (wall or obstacle that cannot get infected or spread infection)
The simulation runs in synchronized time steps (t = 1, 2, 3, ...), where all state changes happen simultaneously according to these rules:
-
Infection mechanics: A healthy cell (value
0) becomes infected at time steptonly if it is orthogonally adjacent (sharing an edge: up, down, left, or right) to at leastthresholdcells that are currently infected. -
Recovery process: Once a cell becomes infected, it stays contagious for exactly
durationtime steps. After this period, the cell recovers and gains permanent immunity—it can no longer be infected or infect others.
The simulation ends when no cells remain in the infected state.
Implement a function that calculates how many complete time steps elapse before the simulation terminates (when the count of infected cells drops to zero).
Input Format
grid: A 2D list wheregrid[r][c]is-1,0, or1duration: Number of time steps each infected cell remains contagiousthreshold: Minimum number of infected neighbors required to spread infection
Output Format
Return a single integer: the total number of elapsed time steps until no infected cells remain.
Constraints
1 <= m, n <= 250(grid dimensions)- Each
grid[r][c]is in{-1, 0, 1} 1 <= duration <= 1001 <= threshold <= 4
Examples
Example 1
Input: virus_spread_time([[0, 1, 0], [0, 0, 0], [0, 0, 0]], 2, 1)
Output: 5
Example 2
Input: virus_spread_time([[1, 0, 0], [0, -1, 0], [0, 0, 0]], 3, 2)
Output: 3
Hints
Hint 1
Track when each cell was infected to determine when it will recover, rather than decrementing counters every step
Hint 2
Use a BFS-like approach where you process cells in waves by their infection time
Hint 3
For efficiency, only update neighbor infection counts when cells become or stop being contagious, rather than scanning the entire grid each step
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key challenge is simulating the spread efficiently without scanning the entire grid at every time step. We use an event-driven approach that tracks infections by their timing.
Core Strategy
-
State tracking: Maintain two sets—one for currently infected cells with their remaining contagious time, and one for healthy cells that can still be infected.
-
Synchronous updates: At each time step, determine new infections by counting how many infected neighbors each healthy cell has. Only cells meeting the threshold become infected.
-
Recovery mechanism: Each infected cell has a countdown. We decrement all counters by one each step and remove cells when their countdown reaches zero (recovery).
-
Termination: When no infected cells remain, return the total elapsed time.
Why This Works
- All state changes at time
tare determined by the configuration at timet-1, ensuring proper synchronous simulation. - We only examine cells adjacent to current infections, avoiding unnecessary grid scans.
- Blocked cells (value
-1) are never added to either the healthy or infected sets, so they naturally don't participate. - The infection count for each healthy cell is recomputed from scratch each step, ensuring correctness even as the infected set changes.
Complexity Analysis
-
Time: O(m × n × T) where T is the number of simulation steps. In practice, T is bounded by the grid dimensions plus the duration, since infection spreads at most one cell per step. For each step, we iterate over infected cells (at most m × n) and check their neighbors.
-
Space: O(m × n) to store the sets of infected and healthy cells.
Implementation
from typing import List
def virus_spread_time(grid: List[List[int]], duration: int, threshold: int) -> int:
m, n = len(grid), len(grid[0])
# Track which cells have already been infected (active or recovered)
infected_status = {(r, c): duration for r in range(m) for c in range(n) if grid[r][c] == 1}
healthy_cells = {(r, c) for r in range(m) for c in range(n) if grid[r][c] == 0}
time_passed = 0
neighbors = ((1, 0), (-1, 0), (0, 1), (0, -1))
while infected_status:
time_passed += 1
# Count infected neighbors for each healthy cell based on current infections
neighbor_counts = {}
for r, c in infected_status:
for dr, dc in neighbors:
adj_r, adj_c = r + dr, c + dc
if (adj_r, adj_c) in healthy_cells:
neighbor_counts[(adj_r, adj_c)] = neighbor_counts.get((adj_r, adj_c), 0) + 1
# Determine which cells become infected this step
new_infections = {pos for pos, count in neighbor_counts.items() if count >= threshold}
# Age existing infections and remove those that have recovered
infected_status = {pos: remaining - 1 for pos, remaining in infected_status.items() if remaining > 1}
# Add newly infected cells
for pos in new_infections:
healthy_cells.remove(pos)
infected_status[pos] = duration
return time_passed