leetcode-317-Shortest Distance from All Buildings
问题
You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:
- Each 0 marks an empty land which you can pass by freely.
- Each 1 marks a building which you cannot pass through.
- Each 2 marks an obstacle which you cannot pass through.
Example:
1 | Input: [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]] |
Note:
There will be at least one building. If it is not possible to build such house according to the above rules, return -1.
分析
从每个为1的点进行广度优先搜索,计算出它到每一个为0的点的距离,累加到该dist数组上,同时统计出每个为0的点所能到达的1的点的个数的总和。遍历所有为0且能够到达1的点的个数为1个总和的点,统计出其最小值。
代码
1 | class Solution { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/15/leetcode-317/
License: 知识共享署名-非商业性使用 4.0 国际许可协议