MediumNo. 1020

Number of Enclaves — LeetCode 1020 Python Solution

Pattern
Union-Find
Topics
Depth-First Search, Breadth-First Search, Union Find, Array, Matrix
Reading time
4 min

The problem

You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.

Example

Input
grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output
3
Explanation
There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.

Python solution

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

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

Complexity

Time
O(V+E)
Space · auxiliary
O(V)

Pattern: Union-Find

Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 1020. Number of Enclaves 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

Related problems
No.ProblemDifficulty
0130Surrounded RegionsMedium
0200Number of IslandsMedium
0695Max Area of IslandMedium
0827Making A Large IslandHard
1254Number of Closed IslandsMedium
1267Count Servers that CommunicateMedium

Frequently asked questions

How hard is LeetCode 1020. Number of Enclaves?

LeetCode 1020. Number of Enclaves is rated Medium on LeetCode.

What is the time complexity of LeetCode 1020. Number of Enclaves?

The Python solution on this page runs in O(V+E).

What is the space complexity of LeetCode 1020. Number of Enclaves?

The Python solution on this page uses O(V) auxiliary space.

What topics does LeetCode 1020. Number of Enclaves cover?

LeetCode 1020. Number of Enclaves 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.

Free to download. Check it runs on your machine, then pick a plan.