Minimum Spread Time for Contamination in a Grid
Trees & GraphsModel answerLast updated
Find how many steps a contamination spreads from multiple sources through a grid, or determine if some cells remain permanently unaffected.
Contamination Spread in a Grid
You are given an m × n grid of cells. Each cell holds one of three values:
0— a blocked cell that contamination cannot enter or pass through1— a clean cell that can become contaminated2— an already-contaminated cell
Every time step, contamination spreads from every contaminated cell to each of its four direct neighbors (up, down, left, right) that is currently clean. All contaminated cells spread simultaneously.
Return the minimum number of time steps required until no clean cell remains anywhere in the grid. If there is at least one clean cell that can never be reached, return -1.
Examples
Input:
2 1 1
1 1 0
0 1 1
Output: 4
Input:
2 1 1
0 1 1
1 0 1
Output: -1 (bottom-left clean cell is walled off)
Input:
0 2 0
Output: 0 (no clean cells to begin with... wait, there are none)
Input:
1 1
Output: -1 (no contaminated source exists)
What is expected
- Describe your algorithm and explain intuitively why it produces the correct answer.
- Analyze time and space complexity.
- Handle all edge cases explicitly.
- Implement the function in the language of your choice.
Function signature (Python)
def min_steps_to_contaminate(grid: List[List[int]]) -> int:
Constraints
1 ≤ m, n ≤ 10- Each cell value is
0,1, or2 - You may not assume there is always at least one contaminated source
Hints
Hint 1
Think about what it means for a clean cell to be contaminated at step k — it must be exactly k hops away from the nearest initially-contaminated cell, with no blocked cells along the path. What algorithm finds shortest distances from multiple sources in one pass?
Hint 2
Instead of running BFS separately from each contaminated source and taking minimums, consider seeding a single BFS queue with all contaminated cells at once at distance 0. This 'virtual super-source' trick finds the nearest-source distance for every reachable cell in O(m·n).
Hint 3
After BFS completes, you need two things to form the answer: the maximum distance seen across all clean cells (that's the step count), and a way to detect whether any clean cell was never reached at all (return -1 in that case). A running counter of remaining clean cells handles both cleanly.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: Multi-Source BFS
Reframing the Problem
The key insight is that the step at which a clean cell gets contaminated equals its shortest 4-directional distance to the nearest initially-contaminated cell, where paths cannot go through blocked (0) cells. The answer is the maximum of that distance across all clean cells. If any clean cell has no path to any source, the answer is -1.
A naive simulation scans the whole grid each step, costing O(mn) per step and O(mn) steps in the worst case — O((mn)²) total. That is unnecessary.
The cleaner approach: seed a BFS queue with every contaminated cell simultaneously at time 0. This is called multi-source BFS. It computes the nearest-source distance for every cell in a single O(mn) pass, because BFS naturally visits cells in nondecreasing order of distance from the combined source set.
Algorithm
- Scan the grid. Enqueue every cell with value
2(all at step 0). Count the clean (1) cells. - If the clean count is already
0, return0. - Run BFS level by level. Each full level represents one time step. For each cell dequeued, inspect its four neighbors. If a neighbor is clean, mark it contaminated, decrement the clean counter, and enqueue it.
- Increment the step counter only after a level that actually contaminated something (avoiding an off-by-one from the final empty expansion).
- Once the queue empties, return the step count if the clean counter hit zero, otherwise
-1.
Correctness Argument
By induction on distance d:
- Base case: cells with
d = 0are contaminated sources — correct by definition. - Inductive step: assume every cell at distance ≤ k is contaminated at exactly its distance. A cell
cat distancek+1has a predecessor neighbor at distancek, which contaminates it at stepk+1. It cannot be contaminated earlier, because that would require a neighbor already contaminated by stepk, implyingd(c) ≤ k— a contradiction.
BFS processes cells in nondecreasing order of distance and marks each cell on its first visit (the shortest path). So the level counter at the time a cell is first reached equals its exact contamination step.
The leftover clean counter catches any cell that BFS never reached — those are walled off by blocked cells or simply have no source anywhere in the grid.
Complexity
- Time:
O(m · n)— each cell is enqueued at most once, and each dequeue checks 4 neighbors. - Space:
O(m · n)— the queue can hold up to all cells in the worst case (e.g., a grid that starts nearly all contaminated). Working on a copy of the grid also costsO(mn); skip it if mutating the input is acceptable.
Edge Cases
| Scenario | Expected output |
|---|---|
| No clean cells anywhere | 0 |
| No contaminated source, but clean cells exist | -1 |
| Clean cells fully surrounded by blocked cells | -1 |
Single cell, value 1 | -1 |
Single cell, value 2 | 0 |
| Single row or column | BFS handles it identically |
The "no clean cells, no sources" case still returns 0 — the goal "no clean cell remains" is already satisfied vacuously.
Implementation
from collections import deque
from typing import List
def min_steps_to_contaminate(grid: List[List[int]]) -> int:
"""
Return the minimum number of steps until no clean cell (1) remains,
or -1 if any clean cell is permanently unreachable.
0 = blocked, 1 = clean, 2 = contaminated. Input grid is not modified.
"""
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
state = [row[:] for row in grid] # copy so we don't mutate the input
queue: deque = deque()
clean = 0
for r in range(rows):
for c in range(cols):
if state[r][c] == 2:
queue.append((r, c))
elif state[r][c] == 1:
clean += 1
if clean == 0:
return 0
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
steps = 0
while queue and clean > 0:
# One full BFS level = one time step of spreading.
for _ in range(len(queue)):
r, c = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and state[nr][nc] == 1:
state[nr][nc] = 2 # mark on enqueue to prevent duplicate visits
clean -= 1
queue.append((nr, nc))
steps += 1
return steps if clean == 0 else -1
Key implementation details:
- Mark on enqueue, not dequeue. If two contaminated neighbors of the same clean cell are processed in the same level, marking on enqueue prevents the cell from being added to the queue twice.
while queue and clean > 0stops the loop the moment the last clean cell is contaminated, so the step counter never gets an extra increment from a trailing empty level.cleancounter avoids a second full-grid scan at the end; it tracks remaining clean cells throughout the BFS.
Trace on Example 1
Initial: Step 1: Step 2: Step 3: Step 4:
2 1 1 2 2 1 2 2 2 2 2 2 2 2 2
1 1 0 2 1 0 2 2 0 2 2 0 2 2 0
0 1 1 0 1 1 0 1 1 0 2 1 0 2 2
(+2 cells) (+2 cells) (+1 cell) (+1 cell)
Answer: 4.
Common Mistakes
- Single-source BFS repeated per source — gives the correct answer but runs in
O(k · mn)forksources. Missing the multi-source trick is the most common gap interviewers look for. - Off-by-one in step counting — incrementing
stepsunconditionally after each level adds a spurious final step when the queue drains without contaminating anything. - Forgetting the no-source case — a grid of all
1s hasclean > 0and an empty queue; the while loop never runs and the function correctly returns-1. - Not handling blocked cells — treating
0cells as passable produces wrong answers on grids where blocked cells wall off sections.