★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-emabwmal-kx.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
You are given a m x n 2D grid initialized with these three possible values.git
-1
- A wall or an obstacle.0
- A gate.INF
- Infinity means an empty room. We use the value 231 - 1 = 2147483647
to represent INF
as you may assume that the distance to a gate is less than 2147483647
.Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF
.github
For example, given the 2D grid:微信
INF -1 0 INF INF INF INF -1 INF -1 INF -1 0 -1 INF INF
After running your function, the 2D grid should be:app
3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4
您將獲得一個由這三個可能值初始化的m x n 2d網格。less
-1
- 牆或障礙物。0
- 門.INF
- 無限意味着一個空房間。咱們使用值2^31-1=2147483647表示inf,由於您能夠假定到門的距離小於2147483647。 把每一個空房間填滿到最近的門的距離。若是不可能到達一個門,應該用inf填充。函數
把每一個空房間填滿到最近的門的距離。若是不可能到達一個門,應該用inf填充。測試
例如,給定二維網格:spa
INF -1 0 INF INF INF INF -1 INF -1 INF -1 0 -1 INF INF
運行函數後,二維網格應爲:rest
3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4
Solution:BFS (Time Limit Exceeded)
1 class Solution { 2 func wallsAndGates(_ rooms:inout [[Int]]) { 3 var q:[(Int,Int)] = [(Int,Int)]() 4 var dirs:[[Int]] = [[0, -1],[-1, 0],[0, 1],[1, 0]] 5 for i in 0..<rooms.count 6 { 7 for j in 0..<rooms[i].count 8 { 9 if rooms[i][j] == 0 10 { 11 q.append((i, j)) 12 } 13 } 14 } 15 while(!q.isEmpty) 16 { 17 let i:Int = q.first!.0 18 let j:Int = q.first!.1 19 q.popLast() 20 for k in 0..<dirs.count 21 { 22 let x:Int = i + dirs[k][0] 23 let y:Int = j + dirs[k][1] 24 if x < 0 || x >= rooms.count || y < 0 || y >= rooms[0].count || rooms[x][y] < rooms[i][j] + 1 25 { 26 continue 27 } 28 rooms[x][y] = rooms[i][j] + 1 29 q.append((x, y)) 30 } 31 } 32 } 33 }
Solution:DFS (嚴重超時產生錯誤)
1 class Solution { 2 func wallsAndGates(_ rooms:inout [[Int]]) { 3 for i in 0..<rooms.count 4 { 5 for j in 0..<rooms[i].count 6 { 7 if rooms[i][j] == 0 8 { 9 dfs(&rooms, i, j, 0) 10 } 11 } 12 } 13 } 14 15 func dfs(_ rooms:inout [[Int]],_ i:Int,_ j:Int,_ val:Int) 16 { 17 if i < 0 || i >= rooms.count || j < 0 || j >= rooms[i].count || rooms[i][j] < val 18 { 19 return 20 } 21 dfs(&rooms, i + 1, j, val + 1) 22 dfs(&rooms, i - 1, j, val + 1) 23 dfs(&rooms, i, j + 1, val + 1) 24 dfs(&rooms, i, j - 1, val + 1) 25 } 26 }
點擊:Playground測試
1 var sol = Solution() 2 let num:Int = Int(Int32.max - 1) 3 var arr:[[Int]] = [[num,-1,0,num],[num,num,num,-1],[num,-1,num,-1],[0,-1,num,num]] 4 sol.wallsAndGates(&arr) 5 print(arr) 6 //Print