Shortest Distance from All Buildings

Hard Graphs Multi source BFS

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 <= 50 where the grid has m rows and n columns.
  • Every cell is 0 (empty land), 1 (building) or 2 (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.

00:00
Testcase

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.

ApproachTimeSpace
Brute force (BFS from every empty cell)O(m² · n²)O(m · n)
BFS from every building with reach countsO(b · m · n)O(m · n)

1Brute force (BFS from every empty cell)

TimeO(m² · n²)Up to m · n searches, each of which can cover the whole grid.
SpaceO(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.

  1. Count the buildings in the grid.
  2. For each empty cell, BFS with a fresh visited matrix, expanding only into empty cells.
  3. When a neighbour is a building, add the distance to it and count it once.
  4. 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;
    }
}

2BFS from every building with reach counts

TimeO(b · m · n)One BFS over the grid per building, for b buildings; pruning only makes later searches smaller.
SpaceO(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.

  1. Keep total[r][c] (sum of distances) and reach[r][c] (buildings that reached the cell); k = buildings processed so far.
  2. 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.
  3. After the BFS, increment k.
  4. 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;
    }
}

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.