Skip to content

Commit 1efac89

Browse files
authored
Update README.md
1 parent 074ba40 commit 1efac89

File tree

1 file changed

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

1 file changed

+56
-0
lines changed

solution/0900-0999/0959.Regions Cut By Slashes/README.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,62 @@ func regionsBySlashes(grid []string) int {
279279
}
280280
```
281281

282+
#### JavaScript
283+
284+
```js
285+
/**
286+
* @param {string[]} grid
287+
* @return {number}
288+
*/
289+
290+
function regionsBySlashes(grid) {
291+
const find = x => {
292+
if (p[x] !== x) {
293+
p[x] = find(p[x]);
294+
}
295+
return p[x];
296+
};
297+
298+
const union = (a, b) => {
299+
const pa = find(a);
300+
const pb = find(b);
301+
if (pa !== pb) {
302+
p[pa] = pb;
303+
size--;
304+
}
305+
};
306+
307+
const n = grid.length;
308+
let size = n * n * 4;
309+
const p = Array.from({ length: size }, (_, i) => i);
310+
311+
for (let i = 0; i < n; i++) {
312+
for (let j = 0; j < n; j++) {
313+
const k = i * n + j;
314+
if (i < n - 1) {
315+
union(4 * k + 2, (k + n) * 4);
316+
}
317+
if (j < n - 1) {
318+
union(4 * k + 1, (k + 1) * 4 + 3);
319+
}
320+
if (grid[i][j] === '/') {
321+
union(4 * k, 4 * k + 3);
322+
union(4 * k + 1, 4 * k + 2);
323+
} else if (grid[i][j] === '\\') {
324+
union(4 * k, 4 * k + 1);
325+
union(4 * k + 2, 4 * k + 3);
326+
} else {
327+
union(4 * k, 4 * k + 1);
328+
union(4 * k + 1, 4 * k + 2);
329+
union(4 * k + 2, 4 * k + 3);
330+
}
331+
}
332+
}
333+
334+
return size;
335+
}
336+
```
337+
282338
<!-- tabs:end -->
283339

284340
<!-- solution:end -->

0 commit comments

Comments
 (0)