Problem Link

Description


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.length
  • n == grid[i].length
  • 1 <= m, n <= 30
  • grid[i][j] is either 0 or 1.

Solution


Python3

class Solution:
    def minDays(self, grid: List[List[int]]) -> int:
        rows, cols = len(grid), len(grid[0])
 
        def countIslands():
            nonlocal grid
 
            visited = [[False] * cols for _ in range(rows)]
            count = 0
 
            def dfs(i, j):
                visited[i][j] = True
 
                for dx, dy in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
                    if 0 <= dx < rows and 0 <= dy < cols and grid[dx][dy] == 1 and not visited[dx][dy]:
                        dfs(dx, dy)
 
            for i in range(rows):
                for j in range(cols):
                    if grid[i][j] == 1 and not visited[i][j]:
                        dfs(i, j)
                        count += 1
 
            return count
        
        count = countIslands()
        
        if count != 1: return 0
 
        for i in range(rows):
            for j in range(cols):
                if grid[i][j] == 1:
                    grid[i][j] = 0
                    count = countIslands()
                    grid[i][j] = 1
 
                    if count != 1: return 1
 
        return 2