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:
0represents empty land where you can build and walk freely1represents an existing building (impassable)2represents 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
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
✓ Linear Growth
Space Complexity
O(mn)
Distance matrix and BFS queue storage
⚡ 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code