Skip to content

Commit 8c17592

Browse files
authored
Update 778-swim-in-rising-water.js
1 parent 48d7ebe commit 8c17592

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

778-swim-in-rising-water.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,51 @@ function dfs(grid, visited, dir, waterHeight, row, col, n) {
3939
}
4040
return false;
4141
}
42+
43+
// another
44+
45+
/**
46+
* @param {number[][]} grid
47+
* @return {number}
48+
*/
49+
class UnionFind {
50+
constructor(N) {
51+
this.id = [];
52+
for (let i = 0; i < N; i++) {
53+
this.id[i] = i;
54+
}
55+
}
56+
57+
root(i) {
58+
while (i != this.id[i]) {
59+
this.id[i] = this.id[this.id[i]];
60+
i = this.id[i];
61+
}
62+
return i;
63+
}
64+
isConnected(p, q) {
65+
return this.root(p) === this.root(q);
66+
}
67+
union(p, q) {
68+
if (this.isConnected(p, q)) return;
69+
this.id[this.root(p)] = this.root(q);
70+
}
71+
}
72+
const swimInWater = grid => {
73+
const N = grid.length;
74+
const uf = new UnionFind(N * N);
75+
let time = 0;
76+
while (!uf.isConnected(0, N * N - 1)) {
77+
for (let i = 0; i < N; i++) {
78+
for (let j = 0; j < N; j++) {
79+
if (grid[i][j] > time) continue;
80+
if (i < N - 1 && grid[i + 1][j] <= time)
81+
uf.union(i * N + j, i * N + j + N);
82+
if (j < N - 1 && grid[i][j + 1] <= time)
83+
uf.union(i * N + j, i * N + j + 1);
84+
}
85+
}
86+
time++;
87+
}
88+
return time - 1;
89+
};

0 commit comments

Comments
 (0)