317. Shortest Distance from All Buildings

You want to build a house on an empty land that reaches all buildings in the shortest total travel distance.

所以要從每個 1 出發去做 bfs, 建構出最小的距離(reaches all buildings 的總距離)

所以需要兩個表:

dist: 總距離表

nums: 可以到幾個建築物, 因為最後計算我們只要能到 reaches all buildings 的點,

nums[i][j] 如果數量 = all buildings 數量, 才是可以蓋房子的空地, 從這裡面找距離最小的

bfs part:

跟往常寫法一樣, 裡面內涵一個 visited[][], 每次跑bfs都會重置, 判斷border

全部跑完後, 最後來找最小距離 (reaches all buildings), 找不到回 -1

time: O(m*n*BFS) = O(m^2*n^2)

space: O(m*n)

Last updated

Was this helpful?