Leetcode 1380 Solution

This article provides solution to leetcode question 1380 (number-of-closed-islands)

https://leetcode.com/problems/number-of-closed-islands

Solution

class Solution:
    def closedIsland(self, grid: List[List[int]]) -> int:
        visited = {}

        m = len(grid)
        n = len(grid[0])

        def check_closed_island(i, j):
            nonlocal grid
            nonlocal visited
            nonlocal m
            nonlocal n

            if (i, j) in visited:
                return visited[(i, j)]

            res = True
            visited[(i, j)] = res

            if i == 0 or i == m - 1 or j == 0 or j == n - 1:
                res = False
            else:
                neighbor_nodes = [
                    (i - 1, j),
                    (i, j - 1),
                    (i, j + 1),
                    (i + 1, j),
                ]

                for i2, j2 in neighbor_nodes:
                    res &= (grid[i2][j2] == 1 or check_closed_island(i2, j2))

            visited[(i, j)] = res
            return res

        ans = 0
        for i in range(m):
            for j in range(n):
                if (i, j) in visited or grid[i][j] == 1:
                    continue

                if check_closed_island(i, j):
                    ans += 1
        return ans