Problem statement

https://binarysearch.com/problems/Enclosed-Islands/

Solution

Similar to Leetcode 1254. Number of Closed Islands, but with only one multi-sorce bfs pass and without dfs pass.

Complexity

It is O(nm) for time and space.

Code

class Solution:
    def solve(self, grid):
        n, m = len(grid[0]), len(grid)
        b1  = [(0, i) for i in range(n)]  + [(i, 0) for i in range(1, m)]
        b2 = [(m-1, i) for i in range(n)] + [(i, n-1) for i in range(m-1)]

        V, cnt = set(), 0
        q = deque([(x, y) for x, y in b1 + b2 if grid[x][y] == 1])
        while q:
            i, j = q.popleft()
            grid[i][j] = 0
            for x, y in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
                if not 0 <= x < m or not 0 <= y < n or grid[x][y] != 1 or (x, y) in V: continue
                V.add((x, y))
                q += [(x, y)]

        return sum(sum(i for i in row) for row in grid)