KatInterview

Virus Spread on a Grid

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphsbfsmatrixmulti-source

Last updated

Tests multi-source BFS on a 2D grid to find the minimum number of rounds for an infection to reach every susceptible cell, or detect if it cannot.

Virus Spread on a Grid

Implement rounds_to_infect_all(grid: List[List[int]]) -> int.

You are given a 2D grid where each cell holds one of three values:

  • 0 — an empty cell with no organism
  • 1 — a healthy cell
  • 2 — an already infected cell

Every round, each infected cell simultaneously spreads the infection to any healthy cell directly adjacent to it (up, down, left, or right). Empty cells (0) are permanently inert: they cannot become infected and they block transmission — infection cannot pass through them.

Return the minimum number of rounds until no healthy cells remain. If one or more healthy cells can never be reached by the infection, return -1.

Rules

  • Return 0 if there are no healthy cells (1s) anywhere in the grid when the process begins, regardless of how many infected or empty cells exist.
  • Return -1 if, after the infection has spread as far as it possibly can, at least one healthy cell still remains.
  • Simultaneous spread: all currently infected cells spread at the same instant each round. A cell that first becomes infected in round k does not spread until round k + 1.
  • There are no ties to break; the answer is a single integer.

Constraints

  • 1 <= rows, cols <= 100
  • Every cell value is 0, 1, or 2
  • Target time complexity: O(rows * cols)
  • Additional space: O(rows * cols)

Examples

Example 1

Input: rounds_to_infect_all([[2, 1, 1], [1, 1, 0], [0, 1, 1]])

Output: 4

Example 2

Input: rounds_to_infect_all([[2, 1, 1], [0, 1, 1], [1, 0, 1]])

Output: -1

Hints

Hint 1

Start by asking: how is this different from a single-source shortest-path problem? Every initially infected cell is a starting point at distance 0 — seed all of them into your search structure before processing any neighbors.

Hint 2

Process the frontier one full round at a time, not one cell at a time. Snapshot how many cells are in the queue at the start of each round and only advance the round counter after that entire batch is drained.

Hint 3

Mark a healthy cell as infected the moment you discover it (when you add it to the queue), not when you pop it. This prevents the same cell from being enqueued multiple times and is also the key to avoiding an off-by-one in the round count.