★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-ztjgfzgp-km.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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:git
For example, given three buildings at (0,0)
, (0,4)
, (2,2)
, and an obstacle at (0,2)
:github
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.app
你想在一片空曠的土地上建造一座房子,它能在最短的距離內到達全部的建築物。你只能上下左右移動。您將獲得一個值爲0、1或2的二維網格,其中:ide
每0分表明一片空地,你能夠自由通行。測試
每1個標記一個不能穿過的建築物。ui
每2個標記一個你不能經過的障礙物。idea
例如,假設(0,0)
, (0,4)
, (2,2)
處有三座建築物,而(0,2)處有障礙物:spa
1 - 0 - 2 - 0 - 1 | | | | | 0 - 0 - 0 - 0 - 0 | | | | | 0 - 0 - 1 - 0 - 0
因爲3+3+1=7的總行程最小,所以點(1,2)是建造房屋的理想空地。因此返回7。
注:
至少有一棟樓。若是沒法按照上述規則建造此類房屋,則返回-1。
Solution:
1 class Solution { 2 func shortestDistance(_ grid:inout [[Int]]) -> Int { 3 var res:Int = Int.max 4 var val:Int = 0 5 var m:Int = grid.count 6 var n:Int = grid[0].count 7 var sum:[[Int]] = grid 8 var dirs:[[Int]] = [[0,-1],[-1,0],[0,1],[1,0]] 9 for i in 0..<grid.count 10 { 11 for j in 0..<grid[i].count 12 { 13 if grid[i][j] == 1 14 { 15 res = Int.max 16 var dist:[[Int]] = grid 17 var q:[(Int,Int)] = [(Int,Int)]() 18 q.append((i, j)) 19 while(!q.isEmpty) 20 { 21 var a:Int = q.first!.0 22 var b:Int = q.first!.1 23 q.removeFirst() 24 for k in 0..<dirs.count 25 { 26 var x:Int = a + dirs[k][0] 27 var y:Int = b + dirs[k][1] 28 if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == val 29 { 30 grid[x][y] -= 1 31 dist[x][y] = dist[a][b] + 1 32 sum[x][y] += (dist[x][y] - 1) 33 q.append((x, y)) 34 res = min(res, sum[x][y]) 35 } 36 } 37 } 38 val -= 1 39 } 40 } 41 } 42 return res == Int.max ? -1 : res 43 } 44 }
點擊:Playground測試
1 var arr:[[Int]] = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]] 2 var sol = Solution() 3 print(sol.shortestDistance(&arr)) 4 //Print 7