All problems

Beacon Territories

Medium · graph traversal

A valley is a rectangular grid of cells. Each cell of grid holds one number:

A walker moves one step at a time to a neighbouring cell (up, down, left or right) that is not rock, and may walk over other beacons' cells freely. A beacon claims an open cell if it is strictly closer, in steps, than every other beacon.

Return a grid of the same size in which:

Examples

Example 1

Input: grid = [[1, 0, 0, 0, 2]]

Output: [[1, 1, 0, 2, 2]]

The middle cell is two steps from both beacons, so nobody claims it.

Example 2

Input: grid = [[1, 0, -1, 0, 2]]

Output: [[1, 1, -1, 2, 2]]

The rock splits the row in two, so each beacon claims the open cell on its own side.

Example 3

Input: grid = [[1, -1, 0], [0, -1, 0]]

Output: [[1, -1, 0], [1, -1, 0]]

The right-hand column is cut off from the only beacon by the rock, so it stays 0.

Constraints