-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add js solution to lc problem: No.1568 (#3400)
- Loading branch information
Showing
3 changed files
with
190 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
60 changes: 60 additions & 0 deletions
60
solution/1500-1599/1568.Minimum Number of Days to Disconnect Island/Solution.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
/** | ||
* @param {number[][]} grid | ||
* @return {number} | ||
*/ | ||
var minDays = function (grid) { | ||
const directions = [ | ||
[0, 1], | ||
[1, 0], | ||
[0, -1], | ||
[-1, 0], | ||
]; | ||
const rows = grid.length; | ||
const cols = grid[0].length; | ||
|
||
function dfs(x, y, visited) { | ||
visited[x][y] = true; | ||
for (let [dx, dy] of directions) { | ||
const nx = x + dx, | ||
ny = y + dy; | ||
if ( | ||
nx >= 0 && | ||
ny >= 0 && | ||
nx < rows && | ||
ny < cols && | ||
grid[nx][ny] === 1 && | ||
!visited[nx][ny] | ||
) { | ||
dfs(nx, ny, visited); | ||
} | ||
} | ||
} | ||
|
||
function countIslands() { | ||
let visited = Array.from({ length: rows }, () => Array(cols).fill(false)); | ||
let count = 0; | ||
for (let i = 0; i < rows; i++) { | ||
for (let j = 0; j < cols; j++) { | ||
if (grid[i][j] === 1 && !visited[i][j]) { | ||
count++; | ||
dfs(i, j, visited); | ||
} | ||
} | ||
} | ||
return count; | ||
} | ||
|
||
if (countIslands() !== 1) return 0; | ||
|
||
for (let i = 0; i < rows; i++) { | ||
for (let j = 0; j < cols; j++) { | ||
if (grid[i][j] === 1) { | ||
grid[i][j] = 0; | ||
if (countIslands() !== 1) return 1; | ||
grid[i][j] = 1; | ||
} | ||
} | ||
} | ||
|
||
return 2; | ||
}; |