File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
solution/0900-0999/0959.Regions Cut By Slashes Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change @@ -279,6 +279,62 @@ func regionsBySlashes(grid []string) int {
279
279
}
280
280
```
281
281
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
+
282
338
<!-- tabs:end -->
283
339
284
340
<!-- solution:end -->
You can’t perform that action at this time.
0 commit comments