Virus Spread on a Grid
Trees & GraphsAuto-graded · 23 test casesLast 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 organism1— a healthy cell2— 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
0if there are no healthy cells (1s) anywhere in the grid when the process begins, regardless of how many infected or empty cells exist. - Return
-1if, 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
kdoes not spread until roundk + 1. - There are no ties to break; the answer is a single integer.
Constraints
1 <= rows, cols <= 100- Every cell value is
0,1, or2 - 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The infection spreads outward from every initially infected cell at the same time, one layer per round. That is exactly what breadth-first search does: it visits all nodes at distance k before any node at distance k + 1. The trick is to treat all starting cells as sources at distance 0 rather than running a separate BFS from each one — this is called multi-source BFS.
Algorithm
- Scan the grid once. Add every cell with value
2to a queue and count cells with value1ashealthy. - While the queue is non-empty and
healthy > 0:- Snapshot the current queue length. Process exactly that many cells (one full round's frontier).
- For each cell, check its four neighbors. If a neighbor is healthy (
1), mark it infected (2), decrementhealthy, and enqueue it. - After the entire batch is processed, increment
rounds.
- Return
roundsifhealthy == 0, otherwise-1.
Why it is correct
Seeding all infected cells into the queue before any processing means the BFS treats them all as being at round 0. Each subsequent layer corresponds to one round of simultaneous spreading. Fixing the iteration count with len(queue) at the start of each round ensures that cells infected this round do not spread until the next — accurately modeling the simultaneous-update rule.
Marking a cell infected when it enters the queue (not when it exits) is essential for two reasons. First, it prevents the same healthy cell from being enqueued by two different infected neighbors in the same round, which would corrupt the healthy count. Second, it ensures those newly infected cells are not processed again in the same round's inner loop.
The healthy guard in the loop condition is equally important. Without it, after the last healthy cell is infected the loop would run one extra iteration, drain the remaining entries from the queue finding no healthy neighbors, and still increment rounds — giving an answer one too high.
Empty cells (0) are never enqueued and their value is never changed, so infection cannot pass through them. Any healthy cell that is completely cut off by empty cells (with no infected cell able to reach it via a path of 1s and 2s) will leave healthy > 0 when the queue empties, correctly triggering the -1 return.
Edge cases
| Scenario | Result |
|---|---|
| No healthy cells at all | healthy starts at 0, loop never runs, returns 0 |
| Healthy cells exist, no infected cells | Queue starts empty, loop never runs, healthy > 0, returns -1 |
| Healthy cell isolated by empty cells | Queue empties before healthy reaches 0, returns -1 |
[[1]] | -1 |
[[2]] or [[0]] | 0 |
| Multiple infected sources meeting in the middle | Multi-source BFS handles naturally; each healthy cell is credited to whichever source reaches it first |
Complexity
- Time:
O(rows * cols)— each cell is enqueued and dequeued at most once; each dequeue inspects at most 4 neighbors; the initial scan is also linear. - Space:
O(rows * cols)— the queue can hold up to all cells in the worst case. No separate visited structure is needed because the grid is updated in place.
from collections import deque
from typing import List
def rounds_to_infect_all(grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
queue = deque()
healthy = 0
# Seed every initially infected cell; count healthy cells.
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
queue.append((r, c))
elif grid[r][c] == 1:
healthy += 1
rounds = 0
# Process one full round (one BFS layer) per iteration.
# The loop stops as soon as no healthy cells remain, preventing
# an extra round from being counted after the last cell is infected.
while queue and healthy:
for _ in range(len(queue)):
r, c = queue.popleft()
for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
grid[nr][nc] = 2 # mark infected at discovery time
healthy -= 1
queue.append((nr, nc))
rounds += 1
return rounds if healthy == 0 else -1