Spreading Pop Wave Across a Square Balloon Grid
Trees & GraphsAuto-graded · 21 test casesLast updated
Compute the earliest time each cell of a square grid is reached by a wave spreading from several seed cells, using multi-source breadth-first search.
Spreading Pop Wave
A square room is laid out as an n x n grid, and every cell holds one balloon. At time 0, the balloons at a given set of seed cells are popped. A balloon that pops at time t pops each of its four direct neighbours (up, down, left, right) at time t + 1, unless that neighbour has already popped earlier or at the same moment. The wave keeps spreading in this way.
Write a function that returns, for every cell, the earliest time at which its balloon pops.
Input
n: the side length of the grid.seeds: a list of[r, c]pairs (row, column, zero-indexed) giving the cells that pop at time0. The same cell may appear more than once.
Output
An n x n list of lists of integers. Entry [r][c] is the earliest pop time of the balloon at row r, column c. If a balloon never pops, the entry is -1.
Rules
- Seed cells have time
0. - Spreading happens only between orthogonally adjacent cells; diagonal cells are not neighbours.
- If
seedsis empty, no balloon ever pops, so every entry is-1.
Constraints
1 <= n <= 500- Every seed satisfies
0 <= r, c < n. seedsmay contain duplicates and may be empty.- Your solution should run in at most about
O(n^2 log(n^2))time.
Examples
Example 1
Input: pop_wave_times(3, [[0, 0]])
Output: [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
Example 2
Input: pop_wave_times(2, [[0, 0], [1, 1]])
Output: [[0, 1], [1, 0]]
Example 3
Input: pop_wave_times(4, [[1, 2]])
Output: [[3, 2, 1, 2], [2, 1, 0, 1], [3, 2, 1, 2], [4, 3, 2, 3]]
Hints
Hint 1
Each cell is a graph node, and every step to a neighbour costs exactly one time unit. The answer for a cell is its shortest distance to the closest seed.
Hint 2
Running a separate search from every seed is too slow when there are many seeds. Instead, put all seeds in the queue together before the search starts.
Hint 3
Record a cell's time at the moment you enqueue it, using -1 as the 'not yet reached' marker. This also protects you from duplicate seeds and from enqueuing a cell more than once.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the grid as a graph where each cell is a node connected to its four orthogonal neighbours, with every edge costing one time unit. The earliest pop time of a cell is then its shortest-path distance to the nearest seed.
Because all edges have equal weight, plain breadth-first search is enough. To handle many seeds at once, use a multi-source BFS: place every seed in the queue at time 0 before starting, then run one ordinary BFS.
Steps:
- Create an
n x nmatrix filled with-1. This value means "not reached yet" and also serves as the visited marker. - For each seed, if its cell is still
-1, set it to0and enqueue it. This skips duplicate seeds. - Repeatedly dequeue a cell. For each in-bounds neighbour still equal to
-1, set it to the current cell's time plus one and enqueue it. - Return the matrix.
Why it is correct
The queue always contains cells with time d followed by cells with time d + 1. All seeds start at time 0, so this holds initially, and processing a cell with time d only adds cells with time d + 1. Cells therefore leave the queue in non-decreasing order of time. The first time a cell is discovered, it is discovered by a cell with the smallest possible time among its neighbours, so the assigned value is the minimum. Later discoveries can only offer equal or larger values and are ignored.
Marking a cell when it is enqueued (rather than when dequeued) ensures each cell enters the queue at most once.
With an empty seed list the queue is empty from the start, so every cell stays -1.
Complexity
- Time:
O(n^2 + k)wherekis the number of seeds. Each cell is enqueued and dequeued at most once and checks four neighbours. - Space:
O(n^2)for the result matrix and the queue.
Reference solution
from collections import deque
from typing import List
def pop_wave_times(n: int, seeds: List[List[int]]) -> List[List[int]]:
times = [[-1] * n for _ in range(n)]
queue = deque()
for r, c in seeds:
if times[r][c] == -1:
times[r][c] = 0
queue.append((r, c))
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
while queue:
r, c = queue.popleft()
next_time = times[r][c] + 1
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n and times[nr][nc] == -1:
times[nr][nc] = next_time
queue.append((nr, nc))
return times