Greenhouse Disease Spread Timer
Trees & GraphsAuto-graded · 21 test casesLast updated
Tests multi-source BFS to find the time until a grid-based propagation process completes or determine impossibility.
You manage a greenhouse represented by an m x n grid. Each cell is one of:
0: bare ground (no plant)1: healthy plant2: diseased plant
Each day, disease spreads from every diseased plant to all orthogonally adjacent (up, down, left, right) healthy plants simultaneously. Bare ground blocks transmission.
Write a function that returns the number of days until every healthy plant becomes diseased. If some healthy plants can never be reached by the disease, return -1.
Constraints:
1 ≤ m, n ≤ 200- Each cell is
0,1, or2 - Your solution should run in
O(m × n)time and useO(m × n)space
Examples
Example 1
Input: days_to_full_infection([[2, 1, 1], [1, 1, 0], [0, 1, 1]])
Output: 4
Example 2
Input: days_to_full_infection([[2, 1, 1], [0, 0, 0], [1, 0, 1]])
Output: -1
Example 3
Input: days_to_full_infection([[2, 2], [2, 2]])
Output: 0
Hints
Hint 1
Start BFS from all diseased plants at once rather than spreading from each individually
Hint 2
Mark cells as diseased when you add them to the queue to avoid revisiting
Hint 3
The answer is the maximum distance any healthy plant is from the nearest initial disease source
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires finding how long it takes for a spreading process to reach all target cells in a grid, starting from multiple sources simultaneously. The natural tool for this is multi-source breadth-first search.
The key insight is that each healthy plant's infection day equals its shortest grid-path distance to any initially diseased plant, where paths can only traverse plant cells (not bare ground). The answer is the maximum such distance across all healthy plants, or -1 if any healthy plant is unreachable.
Algorithm steps:
-
Initialize BFS queue with all disease sources: Scan the grid once. Add every diseased cell
(r, c)to a queue with day0. Count how many healthy plants exist. -
Propagate through BFS layers: Remove cells from the queue. For each cell
(r, c, day), check its four orthogonal neighbors. When you find a healthy neighbor:- Change it to diseased (marks it as visited)
- Decrement the healthy count
- Add it to the queue with
day + 1
-
Track maximum depth: Record the largest
dayvalue seen during BFS traversal. -
Check completion: After BFS finishes, if
healthy_countis zero, all plants were reached—return the maximum day. Otherwise, return-1.
Why this works:
BFS explores cells in order of increasing distance from the sources. By seeding the queue with all diseased plants at distance zero, we effectively simulate simultaneous spreading. Each healthy plant is first discovered at its true infection time, and marking it diseased on discovery prevents revisiting. Cells unreachable through plant neighbors are never processed, leaving healthy_count > 0.
Time complexity: O(m·n). Each cell is enqueued at most once, and we check four neighbors per cell. The initial scan is also O(m·n).
Space complexity: O(m·n). The queue can hold up to m·n cells in the worst case. We modify the grid in place for visited tracking.
Edge cases:
- Empty or single-cell grids return
0or-1as appropriate - Grids with no healthy plants return
0immediately - Grids with healthy plants but no disease sources return
-1 - Healthy plants separated by bare ground from all diseased plants return
-1
from collections import deque
from typing import List
def days_to_full_infection(grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
queue = deque()
healthy_count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
queue.append((r, c, 0))
elif grid[r][c] == 1:
healthy_count += 1
max_days = 0
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
while queue:
row, col, elapsed = queue.popleft()
max_days = max(max_days, elapsed)
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
if (0 <= new_row < rows and 0 <= new_col < cols and
grid[new_row][new_col] == 1):
grid[new_row][new_col] = 2
healthy_count -= 1
queue.append((new_row, new_col, elapsed + 1))
return max_days if healthy_count == 0 else -1