Shortest Distance from All Buildings
Shortest Distance from All Buildings is a hard graphs problem solved with the multi source bfs pattern.
The best approach, bfs from every building with reach counts, runs in O(b · m · n) time and O(m · n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (bfs from every empty cell) up.
Problem
You are given a grid where 0 is empty land you can walk on, 1 is a building and 2 is an obstacle. You want to build a house on one empty cell such that every building can be reached from it by walking up, down, left or right through empty land only (buildings and obstacles cannot be crossed).
Among such cells, choose the one with the smallest total distance: the sum, over all buildings, of the length of the shortest walk from the cell to that building. Return that total, or -1 if no empty cell can reach all buildings.
Examples
Example 1
- Input
grid = [[1,0,0,2,1],[0,0,0,0,0],[0,2,1,0,0]]- Output
7- Why
- From cell (1,2) the three buildings are 3, 3 and 1 steps away, for a total of 7. No other empty cell does better.
Example 2
- Input
grid = [[1,2],[2,0]]- Output
-1- Why
- The only empty cell is fenced off by obstacles, so it cannot reach the building.
Example 3
- Input
grid = [[0,1,0],[0,0,0],[1,0,1]]- Output
4- Why
- Cell (2,1) sits between the two bottom buildings (1 step each) and is 2 steps from the top one.
Constraints
1 <= m, n <= 50where the grid has m rows and n columns.- Every cell is
0(empty land),1(building) or2(obstacle). - There is at least one building.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 16 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (BFS from every empty cell) | O(m² · n²) | O(m · n) |
| BFS from every building with reach counts | O(b · m · n) | O(m · n) |
1Brute force (BFS from every empty cell)
O(m² · n²)Up to m · n searches, each of which can cover the whole grid.O(m · n)The visited matrix and queue of one BFS.Try every empty cell as the meeting spot. A BFS from it through empty land finds the shortest walk to each building; buildings are counted but not walked through. If all buildings were reached, the sum of their distances is a candidate answer.
- Count the buildings in the grid.
- For each empty cell, BFS with a fresh visited matrix, expanding only into empty cells.
- When a neighbour is a building, add the distance to it and count it once.
- If the count equals the number of buildings, update the best total. Return the best, or -1.
class Solution {
public int shortestDistance(int[][] grid) {
int m = grid.length, n = grid[0].length, buildings = 0, best = -1;
int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
for (int[] row : grid)
for (int v : row)
if (v == 1) buildings++;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] != 0) continue;
boolean[][] seen = new boolean[m][n];
seen[i][j] = true;
Queue<int[]> q = new ArrayDeque<>();
q.add(new int[] { i, j });
int dist = 0, found = 0, sum = 0;
while (!q.isEmpty()) {
dist++;
for (int s = q.size(); s > 0; s--) {
int[] c = q.poll();
for (int[] d : dirs) {
int r = c[0] + d[0], k = c[1] + d[1];
if (r < 0 || k < 0 || r >= m || k >= n || seen[r][k]) continue;
seen[r][k] = true;
if (grid[r][k] == 1) {
found++;
sum += dist;
} else if (grid[r][k] == 0) {
q.add(new int[] { r, k });
}
}
}
}
if (found == buildings && (best == -1 || sum < best)) best = sum;
}
}
return best;
}
}class Solution:
def shortestDistance(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
buildings = sum(1 for row in grid for v in row if v == 1)
best = -1
for i in range(m):
for j in range(n):
if grid[i][j] != 0:
continue
seen = [[False] * n for _ in range(m)]
seen[i][j] = True
q = deque([(i, j)])
dist = found = total = 0
while q:
dist += 1
for _ in range(len(q)):
cr, cc = q.popleft()
for dr, dc in dirs:
r, k = cr + dr, cc + dc
if r < 0 or k < 0 or r >= m or k >= n or seen[r][k]:
continue
seen[r][k] = True
if grid[r][k] == 1:
found += 1
total += dist
elif grid[r][k] == 0:
q.append((r, k))
if found == buildings and (best == -1 or total < best):
best = total
return bestclass Solution {
public:
int shortestDistance(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size(), buildings = 0, best = -1;
int dirs[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
for (auto& row : grid)
for (int v : row)
if (v == 1) buildings++;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] != 0) continue;
vector<vector<bool>> seen(m, vector<bool>(n, false));
seen[i][j] = true;
queue<pair<int, int>> q;
q.push({i, j});
int dist = 0, found = 0, sum = 0;
while (!q.empty()) {
dist++;
for (int s = q.size(); s > 0; s--) {
auto [cr, cc] = q.front();
q.pop();
for (auto& d : dirs) {
int r = cr + d[0], k = cc + d[1];
if (r < 0 || k < 0 || r >= m || k >= n || seen[r][k]) continue;
seen[r][k] = true;
if (grid[r][k] == 1) {
found++;
sum += dist;
} else if (grid[r][k] == 0) {
q.push({r, k});
}
}
}
}
if (found == buildings && (best == -1 || sum < best)) best = sum;
}
}
return best;
}
};function shortestDistance(grid) {
const m = grid.length, n = grid[0].length;
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
let buildings = 0, best = -1;
for (const row of grid)
for (const v of row)
if (v === 1) buildings++;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] !== 0) continue;
const seen = Array.from({ length: m }, () => new Array(n).fill(false));
seen[i][j] = true;
let q = [[i, j]];
let dist = 0, found = 0, sum = 0;
while (q.length > 0) {
dist++;
const next = [];
for (const [cr, cc] of q) {
for (const d of dirs) {
const r = cr + d[0], k = cc + d[1];
if (r < 0 || k < 0 || r >= m || k >= n || seen[r][k]) continue;
seen[r][k] = true;
if (grid[r][k] === 1) {
found++;
sum += dist;
} else if (grid[r][k] === 0) {
next.push([r, k]);
}
}
}
q = next;
}
if (found === buildings && (best === -1 || sum < best)) best = sum;
}
}
return best;
}2BFS from every building with reach counts
O(b · m · n)One BFS over the grid per building, for b buildings; pruning only makes later searches smaller.O(m · n)The total and reach matrices plus the BFS queue.Flip the search around: run one BFS from each building over empty land. Each empty cell keeps the total distance from all buildings so far and how many buildings reached it. A cell that some earlier building could not reach can never be the answer, so a later BFS only steps into cells whose reach count equals the number of buildings processed so far; that count also serves as the visited mark.
- Keep
total[r][c](sum of distances) andreach[r][c](buildings that reached the cell);k= buildings processed so far. - For each building, BFS level by level. Step into a neighbour only if it is empty land with
reach == k; then increment its reach and add the current level to its total. - After the BFS, increment k.
- The answer is the smallest total among empty cells with
reach == k(all buildings), or -1 if there is none.
class Solution {
public int shortestDistance(int[][] grid) {
int m = grid.length, n = grid[0].length, k = 0;
int[][] total = new int[m][n], reach = new int[m][n];
int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] != 1) continue;
Queue<int[]> q = new ArrayDeque<>();
q.add(new int[] { i, j });
int dist = 0;
while (!q.isEmpty()) {
dist++;
for (int s = q.size(); s > 0; s--) {
int[] c = q.poll();
for (int[] d : dirs) {
int r = c[0] + d[0], col = c[1] + d[1];
if (r < 0 || col < 0 || r >= m || col >= n) continue;
if (grid[r][col] != 0 || reach[r][col] != k) continue;
reach[r][col]++;
total[r][col] += dist;
q.add(new int[] { r, col });
}
}
}
k++;
}
}
int best = -1;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (grid[i][j] == 0 && reach[i][j] == k && (best == -1 || total[i][j] < best)) best = total[i][j];
return best;
}
}class Solution:
def shortestDistance(self, grid: List[List[int]]) -> int:
m, n, k = len(grid), len(grid[0]), 0
total = [[0] * n for _ in range(m)]
reach = [[0] * n for _ in range(m)]
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for i in range(m):
for j in range(n):
if grid[i][j] != 1:
continue
q = deque([(i, j)])
dist = 0
while q:
dist += 1
for _ in range(len(q)):
cr, cc = q.popleft()
for dr, dc in dirs:
r, col = cr + dr, cc + dc
if r < 0 or col < 0 or r >= m or col >= n:
continue
if grid[r][col] != 0 or reach[r][col] != k:
continue
reach[r][col] += 1
total[r][col] += dist
q.append((r, col))
k += 1
best = -1
for i in range(m):
for j in range(n):
if grid[i][j] == 0 and reach[i][j] == k and (best == -1 or total[i][j] < best):
best = total[i][j]
return bestclass Solution {
public:
int shortestDistance(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size(), k = 0;
vector<vector<int>> total(m, vector<int>(n, 0)), reach(m, vector<int>(n, 0));
int dirs[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] != 1) continue;
queue<pair<int, int>> q;
q.push({i, j});
int dist = 0;
while (!q.empty()) {
dist++;
for (int s = q.size(); s > 0; s--) {
auto [cr, cc] = q.front();
q.pop();
for (auto& d : dirs) {
int r = cr + d[0], col = cc + d[1];
if (r < 0 || col < 0 || r >= m || col >= n) continue;
if (grid[r][col] != 0 || reach[r][col] != k) continue;
reach[r][col]++;
total[r][col] += dist;
q.push({r, col});
}
}
}
k++;
}
}
int best = -1;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (grid[i][j] == 0 && reach[i][j] == k && (best == -1 || total[i][j] < best)) best = total[i][j];
return best;
}
};function shortestDistance(grid) {
const m = grid.length, n = grid[0].length;
let k = 0;
const total = Array.from({ length: m }, () => new Array(n).fill(0));
const reach = Array.from({ length: m }, () => new Array(n).fill(0));
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] !== 1) continue;
let q = [[i, j]];
let dist = 0;
while (q.length > 0) {
dist++;
const next = [];
for (const [cr, cc] of q) {
for (const d of dirs) {
const r = cr + d[0], col = cc + d[1];
if (r < 0 || col < 0 || r >= m || col >= n) continue;
if (grid[r][col] !== 0 || reach[r][col] !== k) continue;
reach[r][col]++;
total[r][col] += dist;
next.push([r, col]);
}
}
q = next;
}
k++;
}
}
let best = -1;
for (let i = 0; i < m; i++)
for (let j = 0; j < n; j++)
if (grid[i][j] === 0 && reach[i][j] === k && (best === -1 || total[i][j] < best)) best = total[i][j];
return best;
}Edge cases to test
- No empty cell can reach every building: return -1
- No empty land at all
- A building enclosed by obstacles, which makes the answer -1
- Empty cells cut off from the rest must not be chosen
- A single building
Hints
Hint 1
You may walk through empty land only; buildings and obstacles block the way, but a building can be the end of a walk.
Hint 2
Searching from every empty cell works but repeats a lot. There are usually far fewer buildings than empty cells.
Hint 3
Run one BFS from each building, adding its distance into a running total for every empty cell it reaches, and count how many buildings reached each cell.
Hint 4
Only cells reached by every building are candidates. A BFS can skip cells that some earlier building already failed to reach.
FAQ
What is the best time complexity for Shortest Distance from All Buildings?
BFS from every building with reach counts runs in O(b · m · n) time and O(m · n) extra space. One BFS over the grid per building, for b buildings; pruning only makes later searches smaller.
Which pattern does Shortest Distance from All Buildings use?
It is a graphs problem that uses the multi source bfs pattern. Other problems with the same pattern: Rotting Oranges, 01 Matrix, Pacific Atlantic Water Flow.
Is there a brute force solution for Shortest Distance from All Buildings?
Yes. Brute force (BFS from every empty cell) takes O(m² · n²) time and O(m · n) space. Try every empty cell as the meeting spot.
Which edge cases should I test for Shortest Distance from All Buildings?
No empty cell can reach every building: return -1; No empty land at all; A building enclosed by obstacles, which makes the answer -1; Empty cells cut off from the rest must not be chosen; A single building.