KatInterview

Virus Spread Simulation with Recovery and Infection Thresholds

Trees & GraphsAuto-graded · 22 test cases
HardAuto-gradedTrees & Graphssimulationbfsgraph-traversal

Last 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 infection
  • 1: Currently infected (patient zero locations at time t = 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:

  1. Infection mechanics: A healthy cell (value 0) becomes infected at time step t only if it is orthogonally adjacent (sharing an edge: up, down, left, or right) to at least threshold cells that are currently infected.

  2. Recovery process: Once a cell becomes infected, it stays contagious for exactly duration time 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 where grid[r][c] is -1, 0, or 1
  • duration: Number of time steps each infected cell remains contagious
  • threshold: 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 <= 100
  • 1 <= 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