-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0778-swim-in-rising-water.java
46 lines (33 loc) · 1.14 KB
/
0778-swim-in-rising-water.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Solution: Greedy Approach with Min Heap
// Time Complexity: O((n^2)*log(n))
class Solution {
private int[][] dirs = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
public int swimInWater(int[][] grid) {
int len = grid.length;
if (len == 1) {
return 0;
}
var seen = new boolean[len][len];
seen[0][0] = true;
var minHeap = new PriorityQueue<Integer[]>((a, b) -> a[0] - b[0]);
minHeap.add(new Integer[] { grid[0][0], 0, 0 });
int result = 0;
while (!minHeap.isEmpty()) {
var curr = minHeap.poll();
result = Math.max(result, curr[0]);
if (curr[1] == len - 1 && curr[2] == len - 1) {
break;
}
for (int i = 0; i < 4; i++) {
int x = curr[1] + dirs[i][0];
int y = curr[2] + dirs[i][1];
if (x < 0 || x >= len || y < 0 || y >= len || seen[x][y]) {
continue;
}
minHeap.add(new Integer[] { grid[x][y], x, y });
seen[x][y] = true;
}
}
return result;
}
}