317 Shortest Distance from All Buildings

1. Question

You want to build a house on anemptyland 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.

For example, given three buildings at(0,0),(0,4),(2,2), and an obstacle at(0,2):

1 - 0 - 2 - 0 - 1
|   |   |   |   |
0 - 0 - 0 - 0 - 0
|   |   |   |   |
0 - 0 - 1 - 0 - 0

The point(1,2)is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7.

Note: There will be at least one building. If it is not possible to build such house according to the above rules, return -1.

2. Implementation

(1) BFS

3. Time & Space Complexity

BFS: 时间复杂度O(M^2N^2),BFS的时间复杂度是O(mn), 总的时间复杂度是 O(# of buildings ) * O(mn), 最坏的情况是每个cell都是building, 总的时间复杂度为O(mn) * O(mn) => O(m^2n^2), 空间复杂度O(mn)

Last updated

Was this helpful?