KatInterview

Spreading Pop Wave Across a Square Balloon Grid

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphsbfsgridmulti-source

Last 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 time 0. 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 seeds is empty, no balloon ever pops, so every entry is -1.

Constraints

  • 1 <= n <= 500
  • Every seed satisfies 0 <= r, c < n.
  • seeds may 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.