Shortest Distance from All Buildings - Problem

Imagine you're a city planner tasked with finding the perfect location for a new house that minimizes travel time to all existing buildings in the city!

You're given an m × n grid representing a city map where:

  • 0 represents empty land where you can build and walk freely
  • 1 represents an existing building (impassable)
  • 2 represents an obstacle like a lake or mountain (impassable)

Your goal is to find an empty land spot that has the shortest total walking distance to all buildings. You can only move up, down, left, or right (no diagonal movement).

Return the minimum total travel distance, or -1 if it's impossible to reach all buildings from any empty land.

Input & Output

example_1.py — Basic Case
$ Input: grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
Output: 7
💡 Note: The optimal house location is at (1,2). From this position: distance to building at (0,0) = 3, distance to building at (0,4) = 3, distance to building at (2,2) = 1. Total distance = 3 + 3 + 1 = 7.
example_2.py — Impossible Case
$ Input: grid = [[1,0,1],[0,2,0],[1,0,1]]
Output: -1
💡 Note: The building at (1,1) is blocked by obstacle (2), so no empty land can reach all buildings. Return -1.
example_3.py — Single Building
$ Input: grid = [[1,0,0],[0,0,0],[0,0,0]]
Output: 2
💡 Note: Only one building exists at (0,0). The farthest empty cell is at (2,2) with distance 4, but the optimal location is (0,1) or (1,0) with distance 1. However, any empty cell works, so minimum distance is from adjacent cell = 1. Actually, let me recalculate: the question asks for shortest total distance, so (0,1) gives distance 1.

Visualization

Tap to expand
🏢 City Planning: Optimal House Location🏢Office A🏢Office B🏠Optimal LocationDistance MatrixEmpty Lot (1,2): Office A=3, Office B=3Empty Lot (2,1): Office A=4, Office B=2Empty Lot (1,1): Office A=2, Office B=2 ✓Total Distances:Lot (1,2): 3+3 = 6Lot (2,1): 4+2 = 6Lot (1,1): 2+2 = 4 (Minimum!)💡 Key Insight: Start BFS from buildings, not empty lots!This avoids redundant distance calculations and is much more efficientTime Complexity: O(k·mn) vs O(m²n²) brute force - Significant improvement!
Understanding the Visualization
1
Survey the City
Identify all buildings (offices) and obstacles (lakes, mountains) in the city grid
2
Measure from Each Office
Instead of checking each empty lot, start from each office and measure walking distances outward
3
Accumulate Commute Times
For each empty lot, add up the walking distances from all offices
4
Choose Optimal Location
Select the empty lot with minimum total commute time to all offices
Key Takeaway
🎯 Key Insight: Instead of trying each empty location and measuring distances to all buildings (expensive), start from each building and measure distances to all empty locations (efficient). This reversal of perspective leads to the optimal Multi-Source BFS solution!

Time & Space Complexity

Time Complexity
⏱️
O(k·mn)

k is number of buildings, we run BFS from each building once through the mn grid

n
2n
Linear Growth
Space Complexity
O(mn)

Distance matrix and BFS queue storage

n
2n
Linearithmic Space

Constraints

  • 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
Asked in
Google 42 Amazon 38 Meta 31 Microsoft 24
58.2K Views
Medium-High Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen