Shortest Distance from All Buildings

Asked atAmazonMeta
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

You are given an m x n grid grid of values 0, 1, or 2, where:

  • each 0 marks an empty land that you can pass by freely,
  • each 1 marks a building that you cannot pass through, and
  • each 2 marks 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. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.

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.

Input: grid = [[1,0]] Output: 1

Input: grid = [[1,0],[0,2],[0,1]]

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 50
  • grid[i][j] is either 0, 1, or 2.
  • There will be at least one building in the grid.

cpp

class Solution {
public:
    int shortestDistance(vector<vector<int>>& grid) {
        // User code goes here
    }
};

java

class Solution {
    public int shortestDistance(int[][] grid) {
        // User code goes here
    }
}

python

class Solution:
    def shortestDistance(self, grid):
        # User code goes here

javascript

class Solution {
    shortestDistance(grid) {
        // User code goes here
    }
}

csharp

public class Solution
{
    public int ShortestDistance(int[][] grid)
    {
        // User code goes here

    }
}

go

func shortestDistance(grid [][]int) int {
    //your code goes here
}
Stuck? Show a way to structure it+
  1. 01For each building, run BFS through empty land.
  2. 02Accumulate distance and reach count per empty cell.
  3. 03Never traverse obstacles or other buildings.
  4. 04After all BFS runs, consider cells reached by every building.
  5. 05Return their minimum distance or minus one.

Reference answer

Then expect these follow-ups

  • How can reach-count pruning reduce later BFS work?

    Tests: follow-up reasoning

  • What changes if each building has a weight?

    Tests: constraint adaptation

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question