Given a rectangular grid containing buildings, empty land, and obstacles, choose an empty cell that minimizes the sum of its shortest-path distances to every building. Return that minimum sum, or -1 if no empty cell can reach every building.
Input
-
grid
: a two-dimensional integer array. A
0
is empty land, a
1
is a building, and a
2
is an obstacle.
Output
Return the minimum total distance as an integer. Return only the distance, so tied locations do not require a tie-break.
Constraints and Edge Cases
-
For this practice version, the grid has between
1
and
50
rows and between
1
and
50
columns.
-
At least one building is present.
-
One move enters an orthogonally adjacent cell and has cost one. Diagonal movement is not allowed.
-
Intermediate cells on a path must be empty land. A building may be the destination, but a path cannot pass through it to reach another building.
-
Obstacles cannot be entered.
-
If no empty land exists, or no empty cell reaches every building, return
-1
.
Example 1
grid = [[1,0,2], [0,0,0], [2,0,1]]
output = 4
The center cell has distance two to each building, for a total of four. No candidate has a smaller sum.
Example 2
grid = [[1,0,1,0,1]]
output = -1
The middle building blocks travel between the two empty cells. Neither candidate can reach all three buildings without passing through a building.