Shortest Distance from All Buildings
Hard
Topics
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
— means some building cannot reach it, which disqualifies the site. The best total here is 7.Input: grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]] Output: 7
Example 2
Input: grid = [[1,0]] Output: 1
Example 3
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
- For each building, BFS outward through empty cells only, level by level.
- Add the level distance into the cell's running total and increment its reach count.
- Use a fresh visited grid per building, since a cell blocked for one building may be open for another.
- 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
bis 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 bestimport java.util.*;
class Solution {
public int shortestDistance(int[][] grid) {
int R = grid.length, C = grid[0].length;
int[][] total = new int[R][C];
int[][] reach = new int[R][C];
int buildings = 0;
int[][] dirs = { {
1,0
},
{
-1,0
},
{
0,1
},
{
0,-1
}
};
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) if (grid[r][c] == 1) {
buildings++;
boolean[][] vis = new boolean[R][C];
vis[r][c] = true;
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{r, c});
int d = 0;
while (!q.isEmpty()) {
int sz = q.size();
d++;
for (int i = 0; i < sz; i++) {
int[] cur = q.poll();
for (int[] dir : dirs) {
int nr = cur[0] + dir[0], nc = cur[1] + dir[1];
if (nr < 0 || nr >= R || nc < 0 || nc >= C || vis[nr][nc] || grid[nr][nc] != 0) continue;
vis[nr][nc] = true;
total[nr][nc] += d;
reach[nr][nc]++;
q.add(new int[]{nr, nc});
}
}
}
}
if (buildings == 0) return -1;
int best = -1;
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) if (grid[r][c] == 0 && reach[r][c] == buildings) {
if (best == -1 || total[r][c] < best) best = total[r][c];
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int shortestDistance(vector<vector<int>>& grid) {
int R = grid.size(), C = grid[0].size();
vector<vector<int>> total(R, vector<int>(C, 0)), reach(R, vector<int>(C, 0));
int buildings = 0;
int dirs[4][2] = { {
1,0
},
{
-1,0
},
{
0,1
},
{
0,-1
}
};
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) if (grid[r][c] == 1) {
buildings++;
vector<vector<char>> vis(R, vector<char>(C, 0));
vis[r][c] = 1;
queue<pair<int,int>> q;
q.push({r, c});
int d = 0;
while (!q.empty()) {
int sz = q.size();
d++;
for (int i = 0; i < sz; i++) {
auto cur = q.front();
q.pop();
for (int k = 0; k < 4; k++) {
int nr = cur.first + dirs[k][0], nc = cur.second + dirs[k][1];
if (nr < 0 || nr >= R || nc < 0 || nc >= C || vis[nr][nc] || grid[nr][nc] != 0) continue;
vis[nr][nc] = 1;
total[nr][nc] += d;
reach[nr][nc]++;
q.push({nr, nc});
}
}
}
}
if (buildings == 0) return -1;
int best = -1;
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) if (grid[r][c] == 0 && reach[r][c] == buildings) {
if (best == -1 || total[r][c] < best) best = total[r][c];
}
return best;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var shortestDistance = function(grid) {
const R = grid.length, C = grid[0].length;
const total = Array.from({ length: R }, () => new Array(C).fill(0));
const reach = Array.from({ length: R }, () => new Array(C).fill(0));
let buildings = 0;
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) if (grid[r][c] === 1) {
buildings++;
const vis = Array.from({ length: R }, () => new Array(C).fill(false));
vis[r][c] = true;
let q = [[r, c]], d = 0;
while (q.length) {
const nq = [];
d++;
for (const [cr, cc] of q) {
for (const [dr, dc] of dirs) {
const nr = cr + dr, nc = cc + dc;
if (nr < 0 || nr >= R || nc < 0 || nc >= C || vis[nr][nc] || grid[nr][nc] !== 0) continue;
vis[nr][nc] = true;
total[nr][nc] += d;
reach[nr][nc]++;
nq.push([nr, nc]);
}
}
q = nq;
}
}
if (buildings === 0) return -1;
let best = -1;
for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) if (grid[r][c] === 0 && reach[r][c] === buildings) {
if (best === -1 || total[r][c] < best) best = total[r][c];
}
return best;
};