Minimize Total Grid Distance to Every Building
WaymoSoftware Engineer · OnsiteLast updated
Find an empty land cell in a 2D grid that minimizes the sum of shortest travel distances to all buildings without traversing through obstacles or other buildings.
Problem Statement
You are given an m x n grid of integers representing a map where each cell contains one of three values:
0: Empty land where a vehicle dispatch hub can be placed.1: A building that needs service.2: An obstacle that vehicles cannot pass through.
You want to place a single dispatch hub on an empty land cell (0) such that the sum of shortest travel distances from the hub to every building (1) is minimized.
A vehicle can only move up, down, left, or right to an adjacent empty land cell (0). Vehicles cannot traverse through obstacles (2) or other buildings (1). The distance between two adjacent cells is 1.
Return the minimum total distance to all buildings. If it is impossible to reach all buildings from any empty land cell, return -1.
Function Interface
def shortest_distance(grid: list[list[int]]) -> int:
pass
Examples
Example 1
Input:
grid = [
[1, 0, 2, 0, 1],
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0]
]
Output: 7
Explanation:
Placing the hub at grid[1][2] allows shortest paths to the three buildings of lengths 3, 3, and 1, respectively. Total distance = 3 + 3 + 1 = 7, which is optimal.
Example 2
Input:
grid = [
[1, 2, 0],
[2, 2, 0],
[0, 0, 1]
]
Output: -1
Explanation:
The building at (0, 0) is surrounded by obstacles and cannot be reached by any empty land cell.
Constraints
m == len(grid)n == len(grid[i])1 <= m, n <= 100grid[i][j]is either0,1, or2.- There is at least one building (
1) on the grid.
Hints
Hint 1
Rather than running BFS from every empty cell, run a BFS from each building to calculate distances to reachable empty cells.
Hint 2
Maintain two matrices: one tracking the cumulative distance to each cell and another tracking the number of buildings that can reach each cell.
Hint 3
To optimize runtime, only expand a BFS into empty cells that were successfully reached by all previously processed buildings.
Follow-up questions
- How would your approach change if the number of buildings greatly exceeds the number of empty land cells?
- How can you mathematically prove that your BFS-pruning optimization guarantees finding the global minimum without missing valid cells?
- How would you adapt the algorithm if cell transitions had non-uniform edge weights (e.g., elevation or traffic delays)?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.