0778. Swim in Rising Water - kumaeki/LeetCode GitHub Wiki
On an N x N
grid, each square grid[i][j]
represents the elevation at that point (i,j)
.
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.
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:
Input: [[0,2],[1,3]]
Output: 3
Explanation:
At time 0, you are in grid location (0, 0).
You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.
You cannot reach point (1, 1) until time 3.
When the depth of water is 3, we can swim anywhere inside the grid.
Example 2:
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.
- grid[i][j] is a permutation of [0, ..., N*N - 1].
首先想到的是用dp, 然后发现不对, 因为除了边界的点之外, 其他的点真的是可以有4个方向的, 并不是只能往右和往下流动.
所以答案就是, 深度优先.
class Solution {
int[] move = new int[]{0, 1, 0, -1, 0};
public int swimInWater(int[][] grid) {
int len = grid.length;
// 记录每个点是否已经计算过
boolean[][] memo = new boolean[len][len];
// 从0,0开始
memo[0][0] = true;
PriorityQueue<Node> que = new PriorityQueue<>((x, y) -> x.e - y.e);
que.offer(new Node(0, 0, grid[0][0]));
while(que.size() > 0){
// 每次从费时最小的点开始计算
Node cur = que.poll();
// 上下左右4个可能的方向
for(int i = 0; i < 4; i++){
int nx = cur.x + move[i];
int ny = cur.y + move[i + 1];
// 如果越界或者已经计算过, 那么跳过
if(nx < 0 || nx >= len || ny < 0 || ny >= len || memo[nx][ny])
continue;
// 计算到达所需的时间
int ne = Math.max(cur.e, grid[nx][ny]);
// 如果是右下角, 那么返回结果
if(nx == len - 1 && ny == len - 1)
return ne;
// 把当前点加入que,进行下一次计算
que.offer(new Node(nx, ny, ne));
memo[nx][ny] = true;
}
}
return -1;
}
class Node{
int x;
int y;
int e;
public Node(int x, int y, int e){
this.x = x;
this.y = y;
this.e = e;
}
}
}