← 返回 waymo 的题目列表Shortest Distance from All Buildings
类型:online_judge
317. Shortest Distance from All Buildings
You are given an m × n grid grid:
0 represents empty land that can be walked through.
1 represents a building.
2 represents an obstacle that cannot be crossed.
Choose an empty cell on which to build a house such that the sum of its shortest-path distances to all buildings is minimized. You may move only up, down, left, or right, and you may not pass through buildings or obstacles.
Return the minimum total distance. Return -1 if no empty cell can reach every building.
Constraints:
1 <= m, n <= 50
grid[i][j] is 0, 1, or 2
There is at least one building.
Example:
Input:
[[1,0,2,0,1],
[0,0,0,0,0],
[0,0,1,0,0]]
Output: 7
Example
Input
[[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
Output
7