File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
solution/1500-1599/1568.Minimum Number of Days to Disconnect Island Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change @@ -295,6 +295,71 @@ func minDays(grid [][]int) int {
295
295
}
296
296
```
297
297
298
+ #### JavaScript
299
+
300
+ ``` js
301
+ /**
302
+ * @param {number[][]} grid
303
+ * @return {number}
304
+ */
305
+ var minDays = function (grid ) {
306
+ const directions = [
307
+ [0 , 1 ],
308
+ [1 , 0 ],
309
+ [0 , - 1 ],
310
+ [- 1 , 0 ],
311
+ ];
312
+ const rows = grid .length ;
313
+ const cols = grid[0 ].length ;
314
+
315
+ function dfs (x , y , visited ) {
316
+ visited[x][y] = true ;
317
+ for (let [dx, dy] of directions) {
318
+ const nx = x + dx,
319
+ ny = y + dy;
320
+ if (
321
+ nx >= 0 &&
322
+ ny >= 0 &&
323
+ nx < rows &&
324
+ ny < cols &&
325
+ grid[nx][ny] === 1 &&
326
+ ! visited[nx][ny]
327
+ ) {
328
+ dfs (nx, ny, visited);
329
+ }
330
+ }
331
+ }
332
+
333
+ function countIslands () {
334
+ let visited = Array .from ({ length: rows }, () => Array (cols).fill (false ));
335
+ let count = 0 ;
336
+ for (let i = 0 ; i < rows; i++ ) {
337
+ for (let j = 0 ; j < cols; j++ ) {
338
+ if (grid[i][j] === 1 && ! visited[i][j]) {
339
+ count++ ;
340
+ dfs (i, j, visited);
341
+ }
342
+ }
343
+ }
344
+ return count;
345
+ }
346
+
347
+ if (countIslands () !== 1 ) return 0 ;
348
+
349
+ for (let i = 0 ; i < rows; i++ ) {
350
+ for (let j = 0 ; j < cols; j++ ) {
351
+ if (grid[i][j] === 1 ) {
352
+ grid[i][j] = 0 ;
353
+ if (countIslands () !== 1 ) return 1 ;
354
+ grid[i][j] = 1 ;
355
+ }
356
+ }
357
+ }
358
+
359
+ return 2 ;
360
+ };
361
+ ```
362
+
298
363
<!-- tabs:end -->
299
364
300
365
<!-- solution:end -->
You can’t perform that action at this time.
0 commit comments