Shortest Distance from All Buildings

Hard

Topics
ArrayBFSMatrix

You are given a grid where 0 is empty land you can travel through, 1 marks a building, and 2 marks an obstacle. Return the shortest total travel distance from an empty land cell that can reach all buildings (moving 4-directionally). If no such cell exists, return -1.

Example 1

0B9█9B1987892109B91001234
buildingbest site
Each empty cell is labelled with the sum of its walking distances to every building; — means some building cannot reach it, which disqualifies the site. The best total here is 7.
2D grid — one row per line.
Input:  grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
Output: 7

Example 2

0B101
buildingbest site
Input:  grid = [[1,0]]
Output: 1

Example 3

0B0
building
The best total here is none.
Input:  grid = [[1]]
Output: -1

Constraints

  • 1 <= m, n <= 50
  • grid[i][j] is 0, 1, or 2
  • There is at least one building.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The answer is a land cell minimising the total walking distance to every building. Searching from each candidate cell to every building is O((m·n)²); searching from each building to every reachable cell is O(buildings · m · n), which is far less because buildings are usually sparse.

So run one breadth-first search per building, and for each empty cell accumulate two numbers: the total distance from all buildings so far, and how many buildings have reached it. A cell is a valid answer only when its reach count equals the building count — that is what rules out cells walled off from part of the map.

Accumulating into shared grids is what keeps this one pass per building rather than one per building-and-cell pair.

Approach

  1. For each building, BFS outward through empty cells only, level by level.
  2. Add the level distance into the cell's running total and increment its reach count.
  3. Use a fresh visited grid per building, since a cell blocked for one building may be open for another.
  4. After all searches, take the minimum total among empty cells whose reach count equals the number of buildings; return -1 if none.

Dry Run

grid    1 0 2 0 1          1 = building, 0 = land, 2 = obstacle
        0 0 0 0 0
        0 0 1 0 0

three buildings: (0,0), (0,4), (2,2)

the cell (1,2)
  from (0,0)  down one, right two   3 steps
  from (0,4)  down one, left two    3 steps
  from (2,2)  up one                1 step
  reach count 3 of 3, total 7

no other cell reachable by all three does better

answer 7

note (0,2) is an obstacle, so the direct route along the top row is blocked --
which is exactly why the reach count is needed rather than assuming connectivity.

Complexity

  • Time — O(b · m · n) where b is the building count. In the worst case every cell is a building, giving O((m·n)²), but then the searches terminate immediately.
  • Space — O(m·n) for the two accumulator grids plus one visited grid, reallocated per building.
  • A common refinement walks buildings in order and decrements a marker so that later searches only traverse cells every previous building reached. That prunes hard on disconnected maps, at the cost of mutating the grid.

Common Pitfalls

  • Searching from every empty cell. That is the O((m·n)²) version and it is what the building-first inversion replaces.
  • Reusing one visited grid across buildings, which stops the second building's search at the first building's frontier.
  • Forgetting the reach count and taking the minimum total among all cells. A cell reached by two of three buildings can have a small total and is not a valid answer.
  • Walking through buildings or obstacles. Only cells holding 0 are traversable, and a building is a source, not a corridor.
  • Counting the building's own cell as a candidate. The answer must be an empty cell.
  • Incrementing the distance per cell rather than per level. The level counter is the distance; tracking it per cell needs a separate distance grid.

Full Solution — all languages

class Solution:
    def shortestDistance(self, grid):
        from collections import deque
        R = len(grid); C = len(grid[0])
        total = [[0] * C for _ in range(R)]
        reach = [[0] * C for _ in range(R)]
        buildings = 0
        dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
        for r in range(R):
            for c in range(C):
                if grid[r][c] == 1:
                    buildings += 1
                    vis = [[False] * C for _ in range(R)]; vis[r][c] = True
                    q = deque([(r, c)]); d = 0
                    while q:
                        d += 1
                        for _ in range(len(q)):
                            cr, cc = q.popleft()
                            for dr, dc in dirs:
                                nr, nc = cr + dr, cc + dc
                                if nr < 0 or nr >= R or nc < 0 or nc >= C or vis[nr][nc] or grid[nr][nc] != 0: continue
                                vis[nr][nc] = True; total[nr][nc] += d; reach[nr][nc] += 1; q.append((nr, nc))
        if buildings == 0: return -1
        best = -1
        for r in range(R):
            for c in range(C):
                if grid[r][c] == 0 and reach[r][c] == buildings:
                    if best == -1 or total[r][c] < best: best = total[r][c]
        return best
Asked at DoorDash
SensAI
Beta
Tap the mic to stop voice mode