-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet-code-q-41.java
More file actions
30 lines (25 loc) · 1.04 KB
/
leet-code-q-41.java
File metadata and controls
30 lines (25 loc) · 1.04 KB
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
class Solution {
public int swimInWater(int[][] grid) {
int m = grid.length, n = grid[0].length;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
int[][] directions = {{0,1}, {1,0}, {0,-1}, {-1,0}};
Set<String> seen = new HashSet<>();
pq.offer(new int[]{grid[0][0], 0, 0});
while (!pq.isEmpty()) {
int[] curr = pq.poll();
int max_d = curr[0], r = curr[1], c = curr[2];
String key = r + "," + c;
if (seen.contains(key)) continue;
seen.add(key);
if (r == m-1 && c == n-1) return max_d;
for (int[] dir : directions) {
int nr = r + dir[0], nc = c + dir[1];
if (nr >= 0 && nr < m && nc >= 0 && nc < n && !seen.contains(nr + "," + nc)) {
int new_d = Math.max(max_d, grid[nr][nc]);
pq.offer(new int[]{new_d, nr, nc});
}
}
}
return -1;
}
}