|
| 1 | +/** |
| 2 | + * 1568. Minimum Number of Days to Disconnect Island |
| 3 | + * https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an m x n binary grid grid where 1 represents land and 0 represents water. An |
| 7 | + * island is a maximal 4-directionally (horizontal or vertical) connected group of 1's. |
| 8 | + * |
| 9 | + * The grid is said to be connected if we have exactly one island, otherwise is said disconnected. |
| 10 | + * |
| 11 | + * In one day, we are allowed to change any single land cell (1) into a water cell (0). |
| 12 | + * |
| 13 | + * Return the minimum number of days to disconnect the grid. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number[][]} grid |
| 18 | + * @return {number} |
| 19 | + */ |
| 20 | +var minDays = function(grid) { |
| 21 | + const rows = grid.length; |
| 22 | + const cols = grid[0].length; |
| 23 | + |
| 24 | + if (countIslands() !== 1) return 0; |
| 25 | + |
| 26 | + for (let r = 0; r < rows; r++) { |
| 27 | + for (let c = 0; c < cols; c++) { |
| 28 | + if (grid[r][c] === 1) { |
| 29 | + grid[r][c] = 0; |
| 30 | + if (countIslands() !== 1) return 1; |
| 31 | + grid[r][c] = 1; |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + return 2; |
| 37 | + |
| 38 | + function countIslands() { |
| 39 | + const visited = Array(rows).fill().map(() => Array(cols).fill(false)); |
| 40 | + let islands = 0; |
| 41 | + |
| 42 | + function dfs(row, col) { |
| 43 | + if (row < 0 || row >= rows || col < 0 || col >= cols |
| 44 | + || visited[row][col] || grid[row][col] === 0) { |
| 45 | + return; |
| 46 | + } |
| 47 | + visited[row][col] = true; |
| 48 | + dfs(row + 1, col); |
| 49 | + dfs(row - 1, col); |
| 50 | + dfs(row, col + 1); |
| 51 | + dfs(row, col - 1); |
| 52 | + } |
| 53 | + |
| 54 | + for (let r = 0; r < rows; r++) { |
| 55 | + for (let c = 0; c < cols; c++) { |
| 56 | + if (grid[r][c] === 1 && !visited[r][c]) { |
| 57 | + islands++; |
| 58 | + dfs(r, c); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + return islands; |
| 63 | + } |
| 64 | +}; |
0 commit comments