Place One Beacon to Minimize Peak Shadow Distance
Trees & GraphsAuto-graded · 21 test casesLast 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) <= 2001 <= len(grid[0]) <= 200- Every row has the same length.
- Every cell is either
0or1. - 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Step 1 — compute existing distances with multi-source BFS
Start a BFS simultaneously from every cell that already holds a beacon. Because every edge costs 1 and movement is 8-directional (with no obstacles), the BFS correctly fills dist[r][c] with the Chebyshev distance to the nearest existing beacon. Cells in a grid with no beacons at all are initialized to a sentinel inf = rows + cols + 1, which exceeds any real distance on the grid, so no special case is needed.
Step 2 — binary search on the answer
Let D be a candidate value for the peak shadow distance. The predicate "is D achievable?" is monotone: if D works, so does any larger value. This makes binary search applicable.
Search between lo = 0 and hi = max(rows, cols). The upper bound is always valid because no two cells on the grid are further apart (Chebyshev) than max(rows, cols) - 1.
Step 3 — feasibility check in O(R × C)
For a given radius D:
- Any cell with
dist[r][c] <= Dis already within range of an existing beacon. No constraint on the new beacon's position comes from it. - Any cell with
dist[r][c] > Dis uncovered. The new beacon must be placed within Chebyshev distanceDof it, meaning inside the axis-aligned square[r - D, r + D] × [c - D, c + D], clipped to grid bounds.
The intersection of any collection of axis-aligned rectangles is itself an axis-aligned rectangle (possibly empty). We maintain the running intersection as [low_r, high_r] × [low_c, high_c], tightening it with each uncovered cell. If the rectangle ever becomes empty, D is infeasible and we return early.
Why it is correct
- If the intersection is non-empty, placing the beacon at any cell inside it brings every uncovered cell within distance
D, and every already-covered cell remains so. - If the intersection is empty, no single grid cell is within
Dof all uncovered cells, so the peak must exceedD. - For
[[0]](single cell, no beacons):dist[0][0] = inf. AtD = 0the uncovered square is exactly[0,0] × [0,0], which is non-empty, so the answer is0. - For grids with no beacons, every cell is uncovered. The algorithm finds the Chebyshev 1-center of the whole grid automatically.
Complexity
Let R and C be the grid dimensions (up to 200 each, so at most 40 000 cells).
- BFS: O(8 · R · C) = O(R · C)
- Each feasibility check: O(R · C)
- Binary search: O(log max(R, C)) iterations — at most 8 for size 200
- Total time: O(R · C · log max(R, C))
- Space: O(R · C) for
distand the BFS queue
Full solution
from collections import deque
from typing import List
def min_peak_shadow(grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
inf = rows + cols + 1
# Build distance-to-nearest-beacon via multi-source BFS.
dist = [[inf] * cols for _ in range(rows)]
queue = deque()
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1:
dist[r][c] = 0
queue.append((r, c))
directions = [
(-1, -1), (-1, 0), (-1, 1),
( 0, -1), (0, 1),
( 1, -1), (1, 0), (1, 1),
]
while queue:
r, c = queue.popleft()
next_dist = dist[r][c] + 1
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] > next_dist:
dist[nr][nc] = next_dist
queue.append((nr, nc))
def feasible(radius: int) -> bool:
# Intersect the Chebyshev squares of every uncovered cell.
low_r, high_r = 0, rows - 1
low_c, high_c = 0, cols - 1
for r in range(rows):
for c in range(cols):
if dist[r][c] > radius:
low_r = max(low_r, r - radius)
high_r = min(high_r, r + radius)
low_c = max(low_c, c - radius)
high_c = min(high_c, c + radius)
if low_r > high_r or low_c > high_c:
return False
return True
lo, hi = 0, max(rows, cols)
while lo < hi:
mid = (lo + hi) // 2
if feasible(mid):
hi = mid
else:
lo = mid + 1
return lo