Calculate Grid Infection Time
Trees & GraphsAuto-graded · 25 test casesLast updated
Tests breadth-first search from multiple sources to model time-based propagation in a grid with obstacles and unreachable regions.
You are given an m x n integer grid where each cell contains one of three values:
0represents a blocked cell1represents a healthy cell2represents an infected cell
Each minute, any healthy cell that shares an edge (up, down, left, right) with an infected cell becomes infected.
Determine the minimum number of minutes required until every healthy cell becomes infected. If any healthy cell cannot be infected, return -1.
Constraints:
0 ≤ m, n ≤ 100grid[i][j]is0,1, or2- Multiple cells may initially be infected
- The grid may be empty or contain no healthy cells
Examples
Example 1
Input: calculate_infection_time([[2, 1, 1], [1, 1, 0], [0, 1, 1]])
Output: 4
Example 2
Input: calculate_infection_time([[2, 1, 1], [0, 1, 1], [1, 0, 1]])
Output: -1
Example 3
Input: calculate_infection_time([[0, 2]])
Output: 0
Hints
Hint 1
Think about this as a graph problem where infection spreads outward from all initially infected cells simultaneously.
Hint 2
Use breadth-first search starting from all infected cells at once to track how far the infection spreads each minute.
Hint 3
Count the healthy cells at the beginning. As each one gets infected, decrement the count. If the count never reaches zero, some cells are unreachable.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires simultaneous propagation from multiple starting points, making it a classic multi-source breadth-first search.
Start by scanning the entire grid to identify all initially infected cells and count the healthy cells. Place every infected cell into a queue to serve as simultaneous starting points for the BFS. If no healthy cells exist, return 0 immediately since no infection needs to occur.
Process the queue level by level, where each level represents one minute of infection spread. For each level, examine every cell in the queue and attempt to infect its four orthogonal neighbors. When a healthy cell becomes infected, mark it as infected in the grid, decrement the healthy count, and add it to the queue for the next level. After processing all cells at the current level, increment the minute counter.
The loop continues while the queue has cells to process and healthy cells remain. When all healthy cells are infected, return the elapsed minutes. If the queue empties while healthy cells still exist, those cells are isolated and cannot be reached, so return -1.
Why It Works
Breadth-first search explores cells in order of increasing distance from the source. With multiple sources, BFS visits each cell at a distance equal to its shortest path to any source. A healthy cell's infection time equals its shortest 4-directional distance to any initially infected cell, which BFS computes naturally.
Processing the queue in discrete levels—handling all cells at distance d before any at distance d+1—ensures each level corresponds to exactly one minute. Marking cells as infected when enqueued prevents revisiting them, maintaining correctness and efficiency.
The stopping condition is precise: once the last healthy cell is infected, no further minutes elapse, and if the queue empties early, unreachable healthy cells remain.
Complexity
Time: O(m × n). Each cell is visited once during the initial scan and enqueued at most once during BFS. Each dequeue operation checks four neighbors, contributing constant work per cell.
Space: O(m × n) for the queue in the worst case, such as when all cells are initially infected. The algorithm modifies the input grid in place to avoid additional visited tracking.
Solution
from collections import deque
from typing import List
def calculate_infection_time(grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
queue = deque()
healthy = 0
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
if healthy == 0:
return 0
minutes = 0
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
healthy -= 1
queue.append((nr, nc))
minutes += 1
return minutes if healthy == 0 else -1