Best Meeting Point Across All Stations in a City Grid
Trees & GraphsAuto-graded · 20 test casesLast updated
Tests multi-source BFS on a grid to find the open cell with the smallest total shortest-path distance to every station, respecting walls and blocked cells.
Problem
You are managing a city grid represented as an m × n matrix. Each cell holds one of three values:
0: An open street where a meeting point can be established.1: A transit station that must be connected to the meeting point.2: A blocked zone that no route may pass through.
Your task is to choose a single open street cell (0) as the meeting point so that the combined shortest travel distance from that cell to every transit station (1) is as small as possible.
Travel is allowed only along the four cardinal directions (up, down, left, right), and only through open street cells (0). Routes may not pass through blocked zones (2) or other transit stations (1). Each step between adjacent cells counts as distance 1.
Return the minimum combined distance. If there is no open cell from which every station is reachable, return -1.
Constraints
m == len(grid)n == len(grid[i])1 <= m, n <= 100grid[i][j]is0,1, or2- There is at least one transit station (
1) in the grid
Examples
Example 1
Input: best_meeting_distance([[1, 0, 2, 0, 1], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0]])
Output: 7
Example 2
Input: best_meeting_distance([[1, 2, 0], [2, 2, 0], [0, 0, 1]])
Output: -1
Hints
Hint 1
Instead of running a search from every open cell, think about flipping the direction: run a search outward from each station instead. The distances are symmetric, so you get the same values with far fewer total operations.
Hint 2
You need two accumulator grids: one that sums up the distances each open cell receives across all station searches, and one that counts how many stations actually reached that cell. A cell is only a valid meeting point if every station reached it.
Hint 3
Standard BFS (queue, visited array, distance incremented level by level) gives exact shortest distances on an unweighted grid. Expand only into cells whose value is 0, and skip anything already visited in the current search.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight: search from stations, not from open cells
The straightforward idea is to run BFS from every open cell and add up its distances to all stations. That works, but it touches O(E · m · n) cells total, where E is the number of open cells — up to ~10⁸ operations on a 100×100 grid.
A cheaper direction: run one BFS per station and let each BFS deposit its distances into shared accumulators. With B stations this costs O(B · m · n), and in most inputs B is much smaller than E.
Two grids track the accumulated information:
distance_sum[r][c]— running total of the shortest distances that every station's BFS has added to this cell.reachable[r][c]— how many stations have successfully reached this cell.
Each BFS starts at the station cell with distance 0 and expands only into cells where grid == 0, leaving obstacles and other stations unvisited. This correctly enforces the movement rule.
After all BFS runs finish, a cell (r, c) qualifies as a meeting point when grid[r][c] == 0 and reachable[r][c] == count (every station reached it). The answer is the smallest distance_sum among qualifying cells, or -1 if none exist.
Why this is correct
BFS on an unweighted grid visits each reachable cell exactly once, at its true shortest distance. Because moves are undirected and uniform-cost, the distance from a station to a cell equals the distance from that cell to the station, so running BFS outward from stations gives us exactly the values we need at each open cell.
The reachable counter is what catches disconnected stations. A station surrounded by walls never increments reachable for any cell, so no cell reaches the required count and -1 is returned — which is the right answer.
Edge cases
- No open cells at all (e.g.,
[[1,1]]): no cell satisfiesgrid[r][c] == 0, so-1. - A station fully enclosed by obstacles or other stations: it reaches nothing, so no cell accumulates a full count.
- Stations in separate connected regions of open land: no single open cell is reachable from all of them, so
-1.
Complexity
- Time:
O(B · m · n)— one BFS per station, each visiting at mostm · ncells. - Space:
O(m · n)— fordistance_sum,reachable, the per-BFSdistgrid, and the BFS queue.
Full solution
from collections import deque
from typing import List
def best_meeting_distance(grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
stations = [(r, c) for r in range(m) for c in range(n) if grid[r][c] == 1]
count = len(stations)
distance_sum = [[0] * n for _ in range(m)]
reachable = [[0] * n for _ in range(m)]
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
for sr, sc in stations:
dist = [[-1] * n for _ in range(m)]
dist[sr][sc] = 0
queue = deque([(sr, sc)])
while queue:
r, c = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n:
if grid[nr][nc] == 0 and dist[nr][nc] == -1:
dist[nr][nc] = dist[r][c] + 1
distance_sum[nr][nc] += dist[nr][nc]
reachable[nr][nc] += 1
queue.append((nr, nc))
answer = None
for r in range(m):
for c in range(n):
if grid[r][c] == 0 and reachable[r][c] == count:
if answer is None or distance_sum[r][c] < answer:
answer = distance_sum[r][c]
return -1 if answer is None else answer
Optional pruning
When processing the k-th station (0-indexed), you can restrict expansion to cells where reachable == k, meaning only cells already reached by all previous stations. Any cell not in this set can never become a valid meeting point, so ignoring it early saves work. If a station's BFS reaches no cell at all under this restriction, you can return -1 immediately. The worst-case bound is unchanged, but practical performance often improves significantly.