Problem 1020

Abstract / Summary

Count the number of land cells completely surrounded by water not connected to the border.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1020.py

class Solution:
    def numEnclaves(self, grid: List[List[int]]) -> int:
        m = len(grid[0])
        n = len(grid)

        # sink into the water (the true meaning of flood-fill ...)
        def sink(x, y):
            if grid[y][x] != 1:
                return

            grid[y][x] = 0

            if x > 0:
                sink(x - 1, y)
            if x < m - 1:
                sink(x + 1, y)
            if y > 0:
                sink(x, y - 1)
            if y < n - 1:
                sink(x, y + 1)

        # convert islands on the boundary to water
        for x in range(m):
            if grid[0][x] != 0:
                sink(x, 0)
            if grid[n - 1][x] != 0:
                sink(x, n - 1)
        for y in range(n):
            if grid[y][0] != 0:
                sink(0, y)
            if grid[y][m - 1] != 0:
                sink(m - 1, y)

        # what's still left ?
        found = 0
        for y in range(1, n - 1):
            for x in range(1, m - 1):
                found += grid[y][x]

        return found
40 lines | 1093 bytes | submitted October 2, 2023 | GitHub   9% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 72% (500k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Breadth First Search
  • Depth First Search
  • Matrix
  • Union Find
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation solves the β€œnumber of enclaves” problem by mutating the input matrix in place. It first eliminates any land cells that are reachable from the outer border, then counts the remaining land cells that are completely surrounded by water. The algorithm is organized around a depth-first flood-fill routine that recursively converts qualifying cells to water.

Key Steps

Dimension extraction

The code extracts the width and height of the grid using the first row and the outer list.

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

These values are used throughout to bound the recursive calls and the subsequent loops.

Recursive flood-fill (sink)

A nested helper function named sink performs a classic flood-fill. It checks whether the current cell contains land (1). If not, the function returns immediately. When land is found, the cell is turned into water (0). The function then recursively explores the four orthogonal neighbours, respecting the grid boundaries.

def sink(x, y):
    if grid[y][x] != 1:
        return

    grid[y][x] = 0

    if x > 0:
        sink(x - 1, y)
    if x < m - 1:
        sink(x + 1, y)
    if y > 0:
        sink(x, y - 1)
    if y < n - 1:
        sink(x, y + 1)

The early exit on non-land cells prevents unnecessary recursion and guarantees termination when the flood reaches water or the edge of the matrix.

Converting border-connected land

Two loops walk the perimeter of the matrix. The first loop iterates over the top and bottom rows; the second loop iterates over the leftmost and rightmost columns. For each border cell that is not water, sink is invoked, which propagates the conversion to all connected land cells.

for x in range(m):
    if grid[0][x] != 0:
        sink(x, 0)
    if grid[n - 1][x] != 0:
        sink(x, n - 1)

for y in range(n):
    if grid[y][0] != 0:
        sink(0, y)
    if grid[y][m - 1] != 0:
        sink(m - 1, y)

By the end of this phase, every land cell that can reach the outer boundary has been turned into water.

Counting remaining enclaves

A nested loop scans the interior of the matrix, excluding the outermost rows and columns. It accumulates the values of the cells, which are now either 0 (water) or 1 (land that could not reach the border). The sum directly yields the number of enclave cells.

found = 0
for y in range(1, n - 1):
    for x in range(1, m - 1):
        found += grid[y][x]

The final result is returned.

return found

Edge Cases Handled

The algorithm gracefully handles grids where the entire matrix consists of water, because the border loops find no land to sink and the final count remains zero. When the grid contains land only on the border, the flood-fill removes all those cells, again leaving a zero count. The recursive sink function checks the cell value before proceeding, which prevents out-of-range recursion when the grid has a single row or column; the boundary checks (x > 0, x < m - 1, y > 0, y < n - 1) ensure that recursive calls never exceed the matrix limits.

If the input grid is empty or has rows of zero length, the initial dimension extraction would raise an exception, but within the intended problem constraints the code assumes a non-empty rectangular matrix, which aligns with typical test cases for this problem.

Performance Optimizations

The solution operates directly on the input grid, eliminating the need for auxiliary data structures such as visited flags or separate copies. This in-place mutation reduces memory overhead and improves cache locality. The early return in sink avoids descending into water cells, limiting recursion to the actual size of each connected land component. By restricting the final counting loop to the interior region (1 to n-2 and 1 to m-2), the algorithm skips the border rows and columns that have already been processed, saving unnecessary iterations. The use of simple integer addition for counting avoids more complex aggregation mechanisms, keeping the inner loop lightweight.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big map made of squares covered in dirt and water. Some dirt squares stick together to form little islands. Some of these islands touch the very edge of the map, and some are floating in the middle away from all the edges.

The goal is to find how many dirt squares are stuck in the middle, far away from the edges.

First, look for any island touching the very edge of the map. When one is found, imagine splashing water all over it until those dirt squares turn into water squares. The special way this works is by checking the top, bottom, left, and right of every dirt square. If one dirt square is connected to another one, the magic splash keeps spreading over to the neighbor until the whole island is gone.

After all those edge islands are turned into water, there is only dirt left in the middle of the map. These are the islands that were safely floating away from the edges. Finally, count every square that is still dirt to find out how many there are in total.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.19 | σ = 0.88

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java
leetcode.ca C++ Java Python Go Rust TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
Garvit244 Python
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
MacJim C++
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
Garvit244 Python
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
MacJim C++
suxrobGM C#
varunu28 Java
32 links | 19 authors | 8 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

14 solutions   October 2, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality