Shortest Distance from All Buildings Problem
Description
LeetCode Problem 317.
You are given an m x n grid grid of values 0, 1, or 2, where:
- each
0marks an empty land that you can pass by freely, - each
1marks a building that you cannot pass through, and - each
2marks an obstacle that you cannot pass through.
You want to build a house on an empty land that reaches all buildings in the shortest total travel distance. You can only move up, down, left, and right.
Return the shortest travel distance for such a house. If it is not possible to build such a house according to the above rules, return -1.
The total travel distance is the sum of the distances between the houses of the friends and the meeting point.
Example 1:

Input: grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
Output: 7
Explanation: Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2).
The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal.
So return 7.
Example 2:
Input: grid = [[1,0]]
Output: 1
Example 3:
Input: grid = [[1]]
Output: -1
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 50grid[i][j]is either0,1, or2.- There will be at least one building in the
grid.
Solution
Approach: BFS from Every Building
Walking distances around obstacles and buildings are shortest paths in a grid, so they come from BFS. Running a BFS from every empty cell would work, but it is cheaper to turn it around: run one BFS from each building and add its distances into every empty cell it reaches.
For each empty cell keep two numbers:
total[r][c]: the sum of the distances from the buildings processed so far.reach[r][c]: how many of those buildings can reach the cell.
A BFS from a building moves only through empty cells (0); buildings and obstacles block it. Each cell it reaches at distance d gets total += d and reach += 1. At the end, the answer is the smallest total among cells whose reach equals the number of buildings, or -1 if there is no such cell.
The tricky case is a cell that some building cannot reach: its total is small precisely because a building is missing from the sum, so we must check reach, not just take the smallest total.
This also gives a simple pruning. When BFS runs from the k-th building (counting from 0), any cell with reach < k already missed an earlier building and can never be the answer, so the BFS only walks cells with reach == k. Setting reach to k + 1 doubles as the visited mark for this BFS, so no separate visited array is needed. If one building is walled in, every later BFS finds nothing, and the answer is -1.
Complexity: O(B · m · n) time, where B is the number of buildings, since each BFS visits every cell at most once, and O(m · n) extra space.
class Solution:
def shortestDistance(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
reach = [[0] * n for _ in range(m)] # how many buildings so far reach this empty cell
total = [[0] * n for _ in range(m)] # sum of the distances from those buildings
k = 0 # buildings done so far
for r in range(m):
for c in range(n):
if grid[r][c] != 1:
continue
# BFS from this building, only through cells that every earlier building reached:
# any other cell can no longer be the answer.
frontier = [(r, c)]
dist = 0
while frontier:
dist += 1
nxt = []
for x, y in frontier:
for nx, ny in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] == 0 and reach[nx][ny] == k:
reach[nx][ny] = k + 1 # also marks the cell as visited in this BFS
total[nx][ny] += dist
nxt.append((nx, ny))
frontier = nxt
k += 1
best = -1
for r in range(m):
for c in range(n):
if grid[r][c] == 0 and reach[r][c] == k and (best == -1 or total[r][c] < best):
best = total[r][c]
return best