778 Swim in Rising Water

1. Question

On an N x Ngrid, each squaregrid[i][j]represents the elevation at that point(i,j).
Now rain starts to fall. At timet, the depth of the water everywhere ist. 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:
1
Input:[[0,2],[1,3]]
2
3
Output:3
4
5
Explanation:
6
At time 0, you are in grid location (0, 0).
7
You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.
8
9
You cannot reach point (1, 1) until time 3.
10
When the depth of water is 3, we can swim anywhere inside the grid.
Copied!
Example 2:
1
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]]
2
3
Output: 16
4
5
Explanation:
6
0 1 2 3 4
7
24 23 22 21 5
8
12 13 14 15 16
9
11 17 18 19 20
10
10 9 8 7 6
11
12
The final route is marked in bold.
13
We need to wait until time 16 so that (0, 0) and (4, 4) are connected.
Copied!
Note:
  1. 1.
    2 <= N <= 50.
  2. 2.
    grid[i][j] is a permutation of [0, ..., N*N - 1].

2. Implementation

(1) Heap
1
class Solution {
2
public int swimInWater(int[][] grid) {
3
if (grid == null || grid.length == 0 || grid[0].length == 0) {
4
return 0;
5
}
6
7
PriorityQueue<CellInfo> minHeap = new PriorityQueue<>();
8
minHeap.add(new CellInfo(0, 0, grid[0][0]));
9
10
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
11
Set<Integer> visited = new HashSet<>();
12
visited.add(0);
13
14
int res = 0;
15
int n = grid.length;
16
17
while (!minHeap.isEmpty()) {
18
CellInfo curCell = minHeap.remove();
19
res = Math.max(res, curCell.height);
20
21
int row = curCell.row, col = curCell.col;
22
23
if (row == n - 1 && col == n - 1) {
24
return res;
25
}
26
27
for (int[] direction : directions) {
28
int nextRow = row + direction[0];
29
int nextCol = col + direction[1];
30
31
if (isValid(grid, nextRow, nextCol, visited)) {
32
minHeap.add(new CellInfo(nextRow, nextCol, grid[nextRow][nextCol]));
33
visited.add(nextRow * n + nextCol);
34
}
35
}
36
}
37
return -1;
38
}
39
40
public boolean isValid(int[][] grid, int row, int col, Set<Integer> visited) {
41
return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && !visited.contains(row * grid[0].length + col);
42
}
43
44
class CellInfo implements Comparable<CellInfo> {
45
int row;
46
int col;
47
int height;
48
49
public CellInfo(int row, int col, int height) {
50
this.row = row;
51
this.col = col;
52
this.height = height;
53
}
54
55
public int compareTo(CellInfo that) {
56
return this.height - that.height;
57
}
58
}
59
}
Copied!
(2) Binary Search
1
Copied!

3. Time & Space Complexity

Heap: 时间复杂度O(mn * log(mn)), 空间复杂度O(mn)