Number of Closed Islands — LeetCode 1254 Python Solution

MediumDepth-First SearchBreadth-First SearchUnion FindArrayMatrix
Problem
#1254
Pattern
Union-Find
Reading time
3 min

The problem

Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.

Example

Input
grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
Output
2
Explanation
Islands in gray are closed because they are completely surrounded by water (group of 1s).

Python solution

Python
class Solution:
    def closedIsland(self, grid: List[List[int]]) -> int:
        def dfs(i: int, j: int) -> int:
            res = int(0 < i < m - 1 and 0 < j < n - 1)
            grid[i][j] = 1
            for a, b in pairwise(dirs):
                x, y = i + a, j + b
                if 0 <= x < m and 0 <= y < n and grid[x][y] == 0:
                    res &= dfs(x, y)
            return res

        m, n = len(grid), len(grid[0])
        dirs = (-1, 0, 1, 0, -1)
        return sum(grid[i][j] == 0 and dfs(i, j) for i in range(m) for j in range(n))

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Union-Find

Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 1254. Number of Closed Islands is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.

The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1254. Number of Closed Islands?
LeetCode 1254. Number of Closed Islands is rated Medium on LeetCode.
What is the time complexity of LeetCode 1254. Number of Closed Islands?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 1254. Number of Closed Islands?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 1254. Number of Closed Islands cover?
LeetCode 1254. Number of Closed Islands is tagged Depth-First Search, Breadth-First Search, Union Find, Array and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview