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:
1
💡 Note:
Only one building exists at (0,0). The optimal empty cell locations are the adjacent cells (0,1) and (1,0), each with distance 1 from the building. The minimum total distance is 1.
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
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code