Optimal Empty Cell with Minimum Path Distance Sum
Trees & GraphsAuto-graded · 22 test casesLast updated
Tests multi-source BFS to find an empty cell minimizing total shortest-path distance to all targets on a grid with obstacles.
You are given an m x n grid where each cell contains one of three values:
0represents an empty cell1represents a target location2represents a blocked cell (obstacle)
Your task is to find an empty cell that minimizes the sum of shortest walking distances to every target location. You can only move horizontally or vertically between adjacent empty cells; you cannot walk through targets or obstacles.
Return the minimum possible sum of distances. If no empty cell can reach all targets, return -1.
Constraints
1 ≤ m, n ≤ 50- At least one target location exists in the grid
- Distance is measured by the shortest path length, not Manhattan distance
- An empty cell is valid only if every target location can reach it through empty cells
Examples
Example 1
Input: optimal_meeting_cell([[1, 0, 0], [0, 0, 0], [0, 0, 1]])
Output: 4
Example 2
Input: optimal_meeting_cell([[1, 0, 2], [2, 2, 2], [0, 0, 1]])
Output: -1
Hints
Hint 1
Consider running BFS from each target location rather than from every empty cell—this is more efficient when targets are sparse.
Hint 2
Track two pieces of information per cell: the total distance accumulated from all targets, and how many targets successfully reached that cell.
Hint 3
A cell is only valid if the count of targets that reached it equals the total number of targets in the grid.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is computing true shortest-path distances on a grid where obstacles and target locations block movement. Manhattan distance does not apply here because paths must navigate around blocked cells.
Since the grid is an unweighted graph (each step costs 1), breadth-first search computes exact shortest paths. The key insight is to reverse the perspective: instead of searching from every empty cell, launch one BFS from each target location.
For each target, run BFS that expands only through empty cells:
- Maintain two accumulator grids across all BFS runs
total_dist[r][c]: cumulative sum of distances from all targets that reached cell(r, c)reach_count[r][c]: number of targets that successfully reached cell(r, c)
After processing all targets, an empty cell is valid only if reach_count equals the total number of targets. Among valid cells, return the minimum total_dist. If no valid cell exists, return -1.
Why It Works
BFS discovers cells in nondecreasing distance order, so the first visit to each cell records the shortest path from that target. By marking cells visited when enqueued, each target contributes exactly one distance per reachable cell.
The reachability check is critical: a cell that only some targets can reach will have a deceptively low sum in total_dist. Filtering by reach_count == target_count ensures we only consider cells reachable by every target.
Distance summation is separable across targets, so accumulating each target's contribution independently and summing them is correct.
Complexity
Let T be the number of targets and M × N the grid dimensions.
- Time: O(T · M · N) — Each BFS visits at most
M · Ncells with constant work per cell (checking four neighbors). The final scan isO(M · N). - Space: O(M · N) — Two accumulator grids plus one queue and visited set per BFS, each bounded by grid size.
With constraints M, N ≤ 50, even if all 2,500 cells were targets, total operations remain well under typical limits.
Solution Code
from collections import deque
from typing import List
def optimal_meeting_cell(grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return -1
m, n = len(grid), len(grid[0])
targets = [(r, c) for r in range(m) for c in range(n) if grid[r][c] == 1]
if not targets:
return -1
total_dist = [[0] * n for _ in range(m)]
reach_count = [[0] * n for _ in range(m)]
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
for sr, sc in targets:
queue = deque([(sr, sc, 0)])
visited = {(sr, sc)}
while queue:
r, c, dist = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if not (0 <= nr < m and 0 <= nc < n):
continue
if grid[nr][nc] != 0 or (nr, nc) in visited:
continue
visited.add((nr, nc))
total_dist[nr][nc] += dist + 1
reach_count[nr][nc] += 1
queue.append((nr, nc, dist + 1))
target_count = len(targets)
best = min((total_dist[r][c] for r in range(m) for c in range(n) if grid[r][c] == 0 and reach_count[r][c] == target_count), default=None)
return best if best is not None else -1