Skip to content

Commit e5fa6c1

Browse files
authored
Update README_EN.md
1 parent 789662e commit e5fa6c1

File tree

1 file changed

+65
-0
lines changed
  • solution/1500-1599/1568.Minimum Number of Days to Disconnect Island

1 file changed

+65
-0
lines changed

solution/1500-1599/1568.Minimum Number of Days to Disconnect Island/README_EN.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,71 @@ func minDays(grid [][]int) int {
286286
}
287287
```
288288

289+
#### JavaScript
290+
291+
```js
292+
/**
293+
* @param {number[][]} grid
294+
* @return {number}
295+
*/
296+
var minDays = function (grid) {
297+
const directions = [
298+
[0, 1],
299+
[1, 0],
300+
[0, -1],
301+
[-1, 0],
302+
];
303+
const rows = grid.length;
304+
const cols = grid[0].length;
305+
306+
function dfs(x, y, visited) {
307+
visited[x][y] = true;
308+
for (let [dx, dy] of directions) {
309+
const nx = x + dx,
310+
ny = y + dy;
311+
if (
312+
nx >= 0 &&
313+
ny >= 0 &&
314+
nx < rows &&
315+
ny < cols &&
316+
grid[nx][ny] === 1 &&
317+
!visited[nx][ny]
318+
) {
319+
dfs(nx, ny, visited);
320+
}
321+
}
322+
}
323+
324+
function countIslands() {
325+
let visited = Array.from({ length: rows }, () => Array(cols).fill(false));
326+
let count = 0;
327+
for (let i = 0; i < rows; i++) {
328+
for (let j = 0; j < cols; j++) {
329+
if (grid[i][j] === 1 && !visited[i][j]) {
330+
count++;
331+
dfs(i, j, visited);
332+
}
333+
}
334+
}
335+
return count;
336+
}
337+
338+
if (countIslands() !== 1) return 0;
339+
340+
for (let i = 0; i < rows; i++) {
341+
for (let j = 0; j < cols; j++) {
342+
if (grid[i][j] === 1) {
343+
grid[i][j] = 0;
344+
if (countIslands() !== 1) return 1;
345+
grid[i][j] = 1;
346+
}
347+
}
348+
}
349+
350+
return 2;
351+
};
352+
```
353+
289354
<!-- tabs:end -->
290355

291356
<!-- solution:end -->

0 commit comments

Comments
 (0)