★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-ahlabvti-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
On an N x N grid
, each square grid[i][j]
represents the elevation at that point (i,j)
.git
Now rain starts to fall. At time t
, the depth of the water everywhere is t
. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t
. You can swim infinite distance in zero time. Of course, you must stay within the boundaries of the grid during your swim.github
You start at the top left square (0, 0)
. What is the least time until you can reach the bottom right square (N-1, N-1)
?微信
Example 1:ide
Input: [[0,2],[1,3]] Output: 3 Explanation: At time , you are in grid location . You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point until time . When the depth of water is , we can swim anywhere inside the grid. 0(0, 0)(1, 1)33
Example 2:spa
Input: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]] Output: 16 Explanation: 0 1 2 3 4 24 23 22 21 5 12 13 14 15 16 11 17 18 19 20 10 9 8 7 6 The final route is marked in bold. We need to wait until time 16 so that (0, 0) and (4, 4) are connected.Note:
2 <= N <= 50
.在一個 N x N 的座標方格 grid
中,每個方格的值 grid[i][j]
表示在位置 (i,j)
的平臺高度。code
如今開始下雨了。當時間爲 t
時,此時雨水致使水池中任意位置的水位爲 t
。你能夠從一個平臺遊向四周相鄰的任意一個平臺,可是前提是此時水位必須同時淹沒這兩個平臺。假定你能夠瞬間移動無限距離,也就是默認在方格內部遊動是不耗時的。固然,在你游泳的時候你必須待在座標方格里面。htm
你從座標方格的左上平臺 (0,0) 出發。最少耗時多久你才能到達座標方格的右下平臺 (N-1, N-1)
?blog
示例 1:get
輸入: [[0,2],[1,3]] 輸出: 3 解釋: 時間爲0時,你位於座標方格的位置爲 此時你不能遊向任意方向,由於四個相鄰方向平臺的高度都大於當前時間爲 0 時的水位。 等時間到達 3 時,你才能夠遊向平臺 (1, 1). 由於此時的水位是 3,座標方格中的平臺沒有比水位 3 更高的,因此你能夠遊向座標方格中的任意位置 (0, 0)。
示例2:
輸入: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]] 輸入: 16 解釋: 0 1 2 3 4 24 23 22 21 5 12 13 14 15 16 11 17 18 19 20 10 9 8 7 6 最終的路線用加粗進行了標記。 咱們必須等到時間爲 16,此時才能保證平臺 (0, 0) 和 (4, 4) 是連通的
提示:
2 <= N <= 50
.1 class Solution { 2 var dirs:[[Int]] = [[0, -1],[-1, 0],[0, 1],[1, 0]] 3 func swimInWater(_ grid: [[Int]]) -> Int { 4 var grid = grid 5 var n:Int = grid.count 6 var dp:[[Int]] = [[Int]](repeating:[Int](repeating:Int.max,count:n),count:n) 7 helper(&grid, 0, 0, grid[0][0], &dp) 8 return dp[n - 1][n - 1] 9 } 10 11 func helper(_ grid:inout [[Int]],_ x:Int,_ y:Int,_ cur:Int,_ dp:inout [[Int]]) 12 { 13 var n:Int = grid.count 14 if x < 0 || x >= n || y < 0 || y >= n || max(cur, grid[x][y]) >= dp[x][y] 15 { 16 return 17 } 18 dp[x][y] = max(cur, grid[x][y]) 19 for dir in dirs 20 { 21 helper(&grid, x + dir[0], y + dir[1], dp[x][y], &dp) 22 } 23 } 24 }