-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0778-swim-in-rising-water.ts
More file actions
35 lines (29 loc) · 927 Bytes
/
0778-swim-in-rising-water.ts
File metadata and controls
35 lines (29 loc) · 927 Bytes
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
function swimInWater(grid: number[][]): number {
const m = grid.length;
const n = grid[0].length;
const heap = new MinPriorityQueue({ priority: (a) => a[0] });
const visited = Array.from({ length: m }, () =>
Array.from({ length: n }, () => false),
);
heap.enqueue([grid[0][0], 0, 0]);
while (!heap.isEmpty()) {
const {
element: [weight, r, c],
} = heap.dequeue();
if (r === m - 1 && c === n - 1) return weight;
const edges = [
[r - 1, c],
[r, c + 1],
[r + 1, c],
[r, c - 1],
];
for (let [nr, nc] of edges) {
if (nr < 0 || nr >= m) continue;
if (nc < 0 || nc >= n) continue;
if (visited[nr][nc]) continue;
visited[nr][nc] = true;
heap.enqueue([Math.max(grid[nr][nc], weight), nr, nc]);
}
}
return 0;
}