Best Meeting Cell on a Grid with Walls
Trees & GraphsAuto-graded · 23 test casesLast updated
Find the open cell with the smallest total shortest-path distance to a set of target cells on a grid with obstacles, using BFS and reachability counting.
You are given a rectangular grid and a list of target cells. Choose one open cell as a meeting point so that the total walking distance from that cell to every target is as small as possible.
Grid and movement
gridis a list ofmrows withnintegers each.0marks an open cell and-1marks an obstacle.- You may move one step up, down, left, or right per move. Each move costs 1.
- You may only step onto open cells.
Targets
targetsis a list of[row, col]pairs, using 0-indexed coordinates.- The same cell may appear more than once. Each occurrence counts separately in the total.
Task
The meeting cell must be open. It may coincide with a target cell. Its cost is the sum, over all entries of targets, of the shortest walking distance from the meeting cell to that target.
Return a two-element list [best_total, [row, col]], where best_total is the minimum possible cost and [row, col] is the meeting cell that achieves it.
Tie-break: if several cells reach the minimum cost, return the one with the smallest row, and among those the smallest column.
Special cases
- If the grid has no rows or no columns, return
[-1, None]. - If
targetsis empty, return[0, [row, col]]for the first open cell in row-major order, or[-1, None]if the grid has no open cell. - If any target lies outside the grid or on an obstacle, return
[-1, None]. - If no open cell can reach every target (for example, walls separate the targets), return
[-1, None].
Constraints
0 <= m, nand the grid is rectangular (all rows have the same length).- Each grid value is either
0or-1. 0 <= len(targets), andlen(targets)is small enough that running a search per target on the grid is feasible.- Distances are measured by walking around obstacles, not by straight-line Manhattan distance.
Examples
Example 1
Input: best_meeting_cell([[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0], [2, 2]])
Output: [4, [0, 0]]
Example 2
Input: best_meeting_cell([[0, 0, -1, 0, 0], [0, 0, -1, 0, 0]], [[0, 0], [0, 4]])
Output: [-1, None]
Example 3
Input: best_meeting_cell([[0, 0, 0], [0, -1, 0], [0, 0, 0]], [[0, 0], [2, 2]])
Output: [4, [0, 0]]
Hints
Hint 1
Manhattan distance is wrong once walls exist. You need true shortest path lengths on an unweighted grid, which is what BFS gives you.
Hint 2
Instead of running a BFS from every candidate cell, run one BFS from each distinct target. Each run gives that target's distance to every cell, so you can add these into a running total per cell.
Hint 3
Keep a second array that counts how many targets reached each cell. A cell is a valid meeting point only if it is open and every target reached it. Scan in row-major order with a strict comparison so ties resolve to the smallest cell.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
First handle the trivial cases directly: an empty grid, an empty target list, and any target that is out of bounds or on an obstacle.
The cost of a meeting cell x is sum over targets t of dist(t, x). Walking distance is symmetric, so dist(t, x) is the same whether we start the search at t or at x. That lets us run one BFS per target instead of one BFS per candidate cell.
- Merge duplicate targets into a map from cell to multiplicity
w. This saves BFS runs without changing any totals. - For each distinct target, run a BFS over open cells. For every cell it reaches at distance
d, addw * dtototal[cell]and addwtoreach[cell]. - A cell is a valid meeting point if it is open and
reach[cell]equals the full number of targets, meaning every target can reach it. - Scan cells in row-major order and keep the first cell with the strictly smallest
total. Because the scan is row-major and the comparison is strict, ties resolve to the smallest row and then the smallest column. - If no cell is valid, return
[-1, None].
Why it is correct
- BFS on an unweighted graph dequeues cells in nondecreasing distance order, so the recorded distance is the true shortest path length.
- The cost is a sum over targets, so adding each target's distances into a per-cell total yields the exact cost for every cell reached by all targets.
- A cell missing from any target's BFS has infinite cost. The
reachcount excludes exactly those cells. - Every open cell is examined, so the minimum is exact, and the scan order enforces the tie-break.
Complexity
Let k be the number of distinct targets.
- Time:
O(k * m * n), since each BFS touches each cell and its at most four edges once, plus anO(m * n)final scan. - Space:
O(m * n)fortotal,reach, and the reused-size distance array and queue.
Reference solution
from collections import deque
from typing import List
def best_meeting_cell(grid: List[List[int]], targets: List[List[int]]) -> List:
if not grid or not grid[0]:
return [-1, None]
m, n = len(grid), len(grid[0])
if not targets:
for r in range(m):
for c in range(n):
if grid[r][c] == 0:
return [0, [r, c]]
return [-1, None]
weights = {}
for r, c in targets:
if r < 0 or r >= m or c < 0 or c >= n or grid[r][c] != 0:
return [-1, None]
weights[(r, c)] = weights.get((r, c), 0) + 1
need = len(targets)
total = [[0] * n for _ in range(m)]
reach = [[0] * n for _ in range(m)]
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
for (sr, sc), w in weights.items():
dist = [[-1] * n for _ in range(m)]
dist[sr][sc] = 0
queue = deque([(sr, sc)])
while queue:
r, c = queue.popleft()
d = dist[r][c]
total[r][c] += w * d
reach[r][c] += w
for dr, dc in directions:
nr, nc = r + dr, c + dc
if (0 <= nr < m and 0 <= nc < n
and grid[nr][nc] == 0 and dist[nr][nc] == -1):
dist[nr][nc] = d + 1
queue.append((nr, nc))
best_sum = None
best_cell = None
for r in range(m):
for c in range(n):
if grid[r][c] == 0 and reach[r][c] == need:
if best_sum is None or total[r][c] < best_sum:
best_sum = total[r][c]
best_cell = [r, c]
if best_sum is None:
return [-1, None]
return [best_sum, best_cell]