KatInterview

Place One Beacon to Minimize Peak Shadow Distance

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphsbfsbinary-searchgrid

Last updated

Tests binary search on a monotone feasibility predicate combined with multi-source BFS and Chebyshev distance geometry on a 2-D grid.

Place One Beacon to Minimize Peak Shadow Distance

You are given a rectangular grid of 0s and 1s. Each cell containing a 1 is an existing beacon. You must place exactly one additional beacon anywhere on the grid — including a cell that already holds a beacon.

Each cell's shadow distance is the length of the shortest path from that cell to the nearest beacon after your placement. You may move between any two adjacent cells, including diagonals, and every move costs exactly 1.

Return the smallest possible value of the largest shadow distance across all cells.

Task

Implement min_peak_shadow(grid).

How distance works

From cell (r, c) you can step to any of its eight neighbors in one move. With no obstacles, the shortest distance between (r1, c1) and (r2, c2) is max(|r1 - r2|, |c1 - c2|). The set of cells reachable from a point within d steps forms an axis-aligned square of side 2d + 1 centered on that point.

Constraints

  • 1 <= len(grid) <= 200
  • 1 <= len(grid[0]) <= 200
  • Every row has the same length.
  • Every cell is either 0 or 1.
  • The grid may contain no beacons initially.

Examples

Example 1

Input: min_peak_shadow([[0]])

Output: 0

Example 2

Input: min_peak_shadow([[1, 0, 0]])

Output: 1

Example 3

Input: min_peak_shadow([[1, 0], [0, 0]])

Output: 1

Hints

Hint 1

Run a multi-source BFS from every existing beacon simultaneously to find each cell's current distance to its nearest beacon. This takes a single BFS pass.

Hint 2

Binary search on the answer D. For a candidate radius D, every cell whose current distance already satisfies dist ≤ D is fine. Only cells with dist > D are 'uncovered' — your new beacon must lie within Chebyshev distance D of all of them.

Hint 3

The intersection of Chebyshev squares (which are axis-aligned rectangles) is itself a rectangle. Track the running intersection as you scan uncovered cells. If the rectangle ever becomes empty, D is not achievable.