★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(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 }