Skip to content

Commit cd8dc69

Browse files
authored
feat: Solution Js for lc no. 959
1 parent d7972c3 commit cd8dc69

File tree

1 file changed

+52
-0
lines changed
  • solution/0900-0999/0959.Regions Cut By Slashes

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* @param {string[]} grid
3+
* @return {number}
4+
*/
5+
6+
function regionsBySlashes(grid) {
7+
const find = (x) => {
8+
if (p[x] !== x) {
9+
p[x] = find(p[x]);
10+
}
11+
return p[x];
12+
};
13+
14+
const union = (a, b) => {
15+
const pa = find(a);
16+
const pb = find(b);
17+
if (pa !== pb) {
18+
p[pa] = pb;
19+
size--;
20+
}
21+
};
22+
23+
const n = grid.length;
24+
let size = n * n * 4;
25+
const p = Array.from({ length: size }, (_, i) => i);
26+
27+
for (let i = 0; i < n; i++) {
28+
for (let j = 0; j < n; j++) {
29+
const k = i * n + j;
30+
if (i < n - 1) {
31+
union(4 * k + 2, (k + n) * 4);
32+
}
33+
if (j < n - 1) {
34+
union(4 * k + 1, (k + 1) * 4 + 3);
35+
}
36+
if (grid[i][j] === '/') {
37+
union(4 * k, 4 * k + 3);
38+
union(4 * k + 1, 4 * k + 2);
39+
} else if (grid[i][j] === '\\') {
40+
union(4 * k, 4 * k + 1);
41+
union(4 * k + 2, 4 * k + 3);
42+
} else {
43+
union(4 * k, 4 * k + 1);
44+
union(4 * k + 1, 4 * k + 2);
45+
union(4 * k + 2, 4 * k + 3);
46+
}
47+
}
48+
}
49+
50+
return size;
51+
52+
}

0 commit comments

Comments
 (0)