Minimum Number of Days to Disconnect Island Problem
Description
LeetCode Problem 1568.
You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's.
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 any single land cell (1) into a water cell (0).
Return the minimum number of days to disconnect the grid.
Example 1:

Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]
Output: 2
Explanation: We need at least 2 days to get a disconnected grid.
Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island.
Example 2:

Input: grid = [[1,1]]
Output: 2
Explanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 30grid[i][j]is either0or1.
Solution
Approach: The Answer Is 0, 1 or 2
The key fact is that two days are always enough:
- If the island has one or two cells, turning all of them into water leaves no island at all.
- Otherwise, look at the top-most, then left-most land cell
c. There is no land above it or to its left, so it has at most two land neighbors. Removing those neighbors cutscoff, and some other land cell is still there, so there are two islands. The only exception is an island made of exactlycand its two neighbors, an L of three cells, and there removingcalone already splits it.
So we only need to tell 0 and 1 apart from 2:
- If the grid does not have exactly one island (zero islands, or several), the answer is
0. - Otherwise, try every land cell: turn it into water, check again whether there is exactly one island, and put it back. If some cell breaks the island (or was the only land cell), the answer is
1. - If no single cell works, the answer is
2.
Checking "exactly one island" is a flood fill from any land cell: the grid is connected when it reaches every land cell.
Complexity: O((mn)2) time, since each of the mn cells costs one O(mn) flood fill, and O(mn) extra space. With m, n <= 30 that is under a million steps.
class Solution:
def minDays(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def connected() -> bool:
"""True if the land forms exactly one island."""
land = [(i, j) for i in range(m) for j in range(n) if grid[i][j] == 1]
if not land:
return False
seen = {land[0]}
stack = [land[0]]
while stack:
i, j = stack.pop()
for x, y in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
if 0 <= x < m and 0 <= y < n and grid[x][y] == 1 and (x, y) not in seen:
seen.add((x, y))
stack.append((x, y))
return len(seen) == len(land)
if not connected():
return 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
grid[i][j] = 0 # try turning just this cell into water
split = not connected()
grid[i][j] = 1
if split:
return 1
return 2 # two days are always enough (see the explanation)