Grid Contagion with Neighbor-Count Thresholds
Trees & GraphsAuto-graded · 22 test casesLast updated
Compute when each grid cell becomes infected under a synchronous neighbor-count rule, using a multi-source BFS that updates counts incrementally instead of rescanning each round.
Grid Contagion with Neighbor-Count Thresholds
A rectangular grid has m rows and n columns. Each cell (r, c) has a resistance value thresholds[r][c]: the minimum number of infected orthogonal neighbors (up, down, left, right) the cell needs before it becomes infected.
You are also given seeds, a list of (row, col) pairs for cells that are infected from the very start.
The infection advances in synchronous rounds:
- Round 0. Every cell listed in
seedsis infected. In addition, every cell whose threshold is0is infected, even if it is not a seed. - Round
t >= 1. Every not-yet-infected cell that has at leastthresholds[r][c]infected neighbors, counting only cells infected in rounds strictly beforet, becomes infected in roundt. Cells infected in roundtdo not help each other within roundt. - An infected cell stays infected forever and keeps counting toward its neighbors.
Return an m x n grid where each entry is the round in which that cell became infected, or -1 if it never becomes infected.
Notes:
seedsmay be empty and may contain duplicate coordinates.- A seed is infected at round 0 regardless of its threshold.
- A threshold larger than the number of in-grid neighbors of a cell means that cell can never be infected unless it is a seed.
Aim for roughly O(m * n) time. Re-scanning the whole grid every round is too slow when the infection travels along a long winding path.
Constraints
m == len(thresholds),n == len(thresholds[0])1 <= m, n <= 1000andm * n <= 10^60 <= thresholds[r][c] <= 40 <= len(seeds) <= m * n- Every seed coordinate lies inside the grid.
Examples
Example 1
Input: spread_times([[2, 2, 2], [2, 2, 2], [2, 2, 2]], [[0, 0], [0, 2], [2, 0]])
Output: [[0, 1, 0], [1, 2, 3], [0, 3, 4]]
Example 2
Input: spread_times([[1, 0], [3, 1]], [])
Output: [[1, 0], [-1, 1]]
Hints
Hint 1
Think of each infection as an event that tells its neighbors 'one more of your neighbors is infected'. Rather than recounting from scratch each round, keep a running count per cell.
Hint 2
Start a BFS queue containing every round-0 cell (seeds and threshold-0 cells together). When you pop a cell infected at round t, bump the counter of each not-yet-infected neighbor.
Hint 3
When a neighbor's counter reaches its threshold, mark it infected at round t + 1 and enqueue it. Because the queue is FIFO and times only increase by 1, the round numbers come out correct. Never count toward cells that are already infected.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A direct simulation re-examines the whole grid every round, which costs O(rounds * m * n). The number of rounds can be as large as m * n along a snake-shaped path, so this is far too slow.
Instead, treat the process as a multi-source BFS with per-cell counters:
- Create a
timesgrid filled with-1and acountsgrid filled with0(infected neighbors seen so far). - Put every round-0 cell in a FIFO queue with time
0: all threshold-0 cells, plus all seeds not already added (this removes duplicates). - Pop a cell with time
t. For each in-grid neighbor that is still uninfected, increment its counter. If the counter reaches the neighbor's threshold, set its time tot + 1and enqueue it. - Cells that are never enqueued keep
-1.
Why it is correct
- All round-0 cells enter the queue first, and a cell popped at time
tonly produces cells at timet + 1. So the queue is always ordered by non-decreasing time, as in standard BFS, and cells deliver their "I'm infected" signals in round order. - A cell with threshold
k >= 1becomes infected one round after itsk-th earliest infected neighbor. Since signals arrive in time order, the signal that lifts its counter tokcomes from exactly that neighbor, so assigningt + 1is right. - A cell infected at round
t + 1is popped only after every round-tcell, so it cannot contribute within its own round. This matches the synchronous rule. - Already-infected cells (including seeds with large thresholds) are skipped, so they are never re-enqueued.
- If a threshold exceeds a cell's number of in-grid neighbors, its counter can never reach the threshold, so it stays
-1.
Complexity
- Time:
O(m * n + s), wheres = len(seeds). Each cell is enqueued at most once and does at most 4 neighbor checks. - Space:
O(m * n)for the grids and queue.
Reference solution
from collections import deque
from typing import List, Tuple
def spread_times(thresholds: List[List[int]], seeds: List[Tuple[int, int]]) -> List[List[int]]:
m, n = len(thresholds), len(thresholds[0])
times = [[-1] * n for _ in range(m)]
counts = [[0] * n for _ in range(m)]
queue = deque()
# Round 0: all threshold-0 cells.
for r in range(m):
for c in range(n):
if thresholds[r][c] == 0:
times[r][c] = 0
queue.append((r, c))
# Round 0: explicit seeds (skip ones already infected).
for r, c in seeds:
if times[r][c] == -1:
times[r][c] = 0
queue.append((r, c))
dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
while queue:
r, c = queue.popleft()
nxt = times[r][c] + 1
for dr, dc in dirs:
nr, nc = r + dr, c + dc
if nr < 0 or nr >= m or nc < 0 or nc >= n:
continue
if times[nr][nc] != -1:
continue
counts[nr][nc] += 1
if counts[nr][nc] >= thresholds[nr][nc]:
times[nr][nc] = nxt
queue.append((nr, nc))
return times