Python 3 https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/

class Solution:
    def minDays(self, grid: List[List[int]]) -> int:
 
        def islands_number():
            visited = set()
            m, n = len(grid), len(grid[0])
            ans = 0
 
            for i in range(m):
                for j in range(n):
 
                    if grid[i][j] == 1 and (i, j) not in visited:
                        ans += 1
                        queue = collections.deque([(i, j)])
                        visited.add((i, j))
 
                        while queue:
 
                            x, y = queue.popleft()
                            for x1, y1 in ((x+1, y), (x, y+1), (x-1, y), (x, y-1)):
 
                                if 0 <= x1 < m and 0 <= y1 < n and (x1, y1) not in visited and grid[x1][y1] == 1:
                                    queue.append((x1, y1))
                                    visited.add((x1, y1))
 
            return ans
 
        m, n = len(grid), len(grid[0])
 
        if islands_number() > 1:
            return 0
 
        for i in range(m):
            for j in range(n):
 
                if grid[i][j] == 1:
                    grid[i][j] = 0
                    cnt = islands_number()
                    if cnt > 1 or cnt == 0:
                        return 1
                    grid[i][j] = 1
 
        return 2