TRACK B · ALGORITHMmedium•NOVEMBER 2026•6 MIN
Multi-Source BFS: Shortest Path & Simultaneous Wave Spread
Enqueue all starting sources at distance 0 to compute minimum wave time on unweighted graphs and grids.
bfsgraphsgridsshortest-pathqueues
The core idea
BFS explores vertices in non-decreasing hop order, so the FIRST time you reach a cell or node is guaranteed to be the shortest unweighted path. Enqueueing multiple sources together simulates simultaneous spread.
Watch it run
Step through the trace below (or turn on Predict Mode) to watch the invariant hold at every step.
LOADING MULTI-SOURCE BFS GRID SIM...
What to say out loud
Canonical Python template
from collections import deque
def minutes_to_spread(grid: list[list[int]]) -> int:
rows, cols = len(grid), len(grid[0])
q = deque((r, c, 0) for r in range(rows) for c in range(cols) if grid[r][c] == 2)
healthy = sum(cell == 1 for row in grid for cell in row)
mins = 0
while q:
r, c, t = q.popleft()
mins = max(mins, t)
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
q.append((nr, nc, t + 1))
return mins if healthy == 0 else -1