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
Difficulty
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
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Solved On The Same Day
- problem 997: Find the Town Judge
- problem 695: Max Area of Island
- problem 797: All Paths From Source to Target
- problem 802: Find Eventual Safe States
- problem 863: All Nodes Distance K in Binary Tree
- problem 934: Shortest Bridge
- problem 1091: Shortest Path in Binary Matrix
- problem 1129: Shortest Path with Alternating Colors
- problem 1306: Jump Game III
- problem 1376: Time Needed to Inform All Employees
- problem 1557: Minimum Number of Vertices to Reach All Nodes
- problem 2038: Remove Colored Pieces if Both Neighbors are the Same Color
- problem 212: Word Search II
Extra
- 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