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 @@ -269,6 +269,62 @@ func regionsBySlashes(grid []string) int {
269
269
}
270
270
```
271
271
272
+ #### JavaScript
273
+
274
+ ``` js
275
+ /**
276
+ * @param {string[]} grid
277
+ * @return {number}
278
+ */
279
+
280
+ function regionsBySlashes (grid ) {
281
+ const find = x => {
282
+ if (p[x] !== x) {
283
+ p[x] = find (p[x]);
284
+ }
285
+ return p[x];
286
+ };
287
+
288
+ const union = (a , b ) => {
289
+ const pa = find (a);
290
+ const pb = find (b);
291
+ if (pa !== pb) {
292
+ p[pa] = pb;
293
+ size-- ;
294
+ }
295
+ };
296
+
297
+ const n = grid .length ;
298
+ let size = n * n * 4 ;
299
+ const p = Array .from ({ length: size }, (_ , i ) => i);
300
+
301
+ for (let i = 0 ; i < n; i++ ) {
302
+ for (let j = 0 ; j < n; j++ ) {
303
+ const k = i * n + j;
304
+ if (i < n - 1 ) {
305
+ union (4 * k + 2 , (k + n) * 4 );
306
+ }
307
+ if (j < n - 1 ) {
308
+ union (4 * k + 1 , (k + 1 ) * 4 + 3 );
309
+ }
310
+ if (grid[i][j] === ' /' ) {
311
+ union (4 * k, 4 * k + 3 );
312
+ union (4 * k + 1 , 4 * k + 2 );
313
+ } else if (grid[i][j] === ' \\ ' ) {
314
+ union (4 * k, 4 * k + 1 );
315
+ union (4 * k + 2 , 4 * k + 3 );
316
+ } else {
317
+ union (4 * k, 4 * k + 1 );
318
+ union (4 * k + 1 , 4 * k + 2 );
319
+ union (4 * k + 2 , 4 * k + 3 );
320
+ }
321
+ }
322
+ }
323
+
324
+ return size;
325
+ }
326
+ ```
327
+
272
328
<!-- tabs:end -->
273
329
274
330
<!-- solution:end -->
You can’t perform that action at this time.
0 commit comments