1568. Minimum Number of Days to Disconnect Island #303
-
Topics: You are given an The grid is said to be connected if we have exactly one island, otherwise is said disconnected. In one day, we are allowed to change a****ny single land cell Return the minimum number of days to disconnect the grid. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to consider the following steps: Steps to Solve the Problem:
Key Functions:
Let's implement this solution in PHP: 1568. Minimum Number of Days to Disconnect Island <?php
function minDays($grid) {
$m = count($grid);
$n = count($grid[0]);
// Check if the grid is already disconnected
if (countIslands($grid) != 1) {
return 0;
}
// Check if a single land removal disconnects the grid
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($grid[$i][$j] == 1) {
$grid[$i][$j] = 0; // Temporarily convert to water
if (countIslands($grid) != 1) {
return 1;
}
$grid[$i][$j] = 1; // Revert back to land
}
}
}
// Otherwise, it will take 2 days to disconnect the grid
return 2;
}
function countIslands(&$grid) {
$m = count($grid);
$n = count($grid[0]);
$visited = array_fill(0, $m, array_fill(0, $n, false));
$islandCount = 0;
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($grid[$i][$j] == 1 && !$visited[$i][$j]) {
$islandCount++;
dfs($grid, $i, $j, $visited);
}
}
}
return $islandCount;
}
function dfs(&$grid, $i, $j, &$visited) {
$m = count($grid);
$n = count($grid[0]);
$directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
$visited[$i][$j] = true;
foreach ($directions as $dir) {
$ni = $i + $dir[0];
$nj = $j + $dir[1];
if ($ni >= 0 && $nj >= 0 && $ni < $m && $nj < $n && $grid[$ni][$nj] == 1 && !$visited[$ni][$nj]) {
dfs($grid, $ni, $nj, $visited);
}
}
}
// Example usage:
$grid1 = [
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]
];
echo minDays($grid1); // Output: 2
$grid2 = [
[1, 1]
];
echo minDays($grid2); // Output: 2
?> Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to consider the following steps:
Steps to Solve the Problem:
Check Initial Connectivity: First, check if the grid is already disconnected by determining if there is more than one island in the grid. If it's already disconnected, return
0
.Check If Single Removal Disconnects the Island: Iterate through each cell of the grid. Temporarily convert the cell from
1
to0
(if it's1
) and check if the grid becomes disconnected by counting the number of islands. If converting a single cell disconnects the island, return1
.Two Day Disconnection: If no single cell conversion disconnects the island, then the grid can be disconnected by converting any two adjacent land cells. Therefore, …