Problem 1254

Abstract / Summary

Count islands fully surrounded by water in a grid of land and water cells.

Note

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

Python 1254.py

class Solution:
    def closedIsland(self, grid: List[List[int]]) -> int:
        width  = len(grid[0])
        height = len(grid)

        # make room for positive island IDs
        water  = 0
        island = -1
        for y in range(height):
            for x in range(width):
                grid[y][x] -= 1

        # replace 0 with value
        def fill(x, y, value):
            todo = [ (x, y) ]
            while todo:
                x, y = todo.pop()
                if 0 <= x < width and 0 <= y < height and grid[y][x] == island:
                    grid[y][x] = value
                    todo.append((x - 1, y))
                    todo.append((x + 1, y))
                    todo.append((x, y - 1))
                    todo.append((x, y + 1))

        # remove islands on the border
        for x in range(width):
            fill(x,          0, water)
            fill(x, height - 1, water)
        for y in range(height):
            fill(0, y,         water)
            fill(width - 1, y, water)

        count = 0
        for y in range(height):
            for x in range(width):
                if grid[y][x] == island:
                    count += 1
                    fill(x - 1, y, count)
                    fill(x + 1, y, count)
                    fill(x, y - 1, count)
                    fill(x, y + 1, count)

        return count
43 lines | 1408 bytes | submitted October 14, 2023 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 67% (400k+ 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 closedIsland method receives a two-dimensional list representing a map where 0 denotes land and 1 denotes water. Its purpose is to count the number of islands that are completely surrounded by water, i.e., islands that do not touch the outer border of the grid. The algorithm works by first converting the input values, then eliminating any land that reaches the border, and finally labeling the remaining isolated land masses with unique identifiers while counting them.

Key Steps

Normalizing Grid Values

Before any processing begins the code shifts every cell value down by one. This transforms original water cells (1) into 0 and original land cells (0) into -1. The variables water and island are set to 0 and -1 respectively, providing clear symbolic names for the two states used later in the algorithm.

width  = len(grid[0])
height = len(grid)

water  = 0
island = -1
for y in range(height):
    for x in range(width):
        grid[y][x] -= 1

Flood Fill Helper

A nested function fill implements an explicit stack-based flood fill. It receives a starting coordinate and a replacement value. While the stack is not empty, the function pops a coordinate, checks bounds, and verifies that the current cell matches the target island marker (-1). If so, the cell is overwritten with the supplied value and its four orthogonal neighbours are pushed onto the stack. Using a list as a stack avoids recursion depth limits and keeps the operation iterative.

def fill(x, y, value):
    todo = [(x, y)]
    while todo:
        x, y = todo.pop()
        if 0 <= x < width and 0 <= y < height and grid[y][x] == island:
            grid[y][x] = value
            todo.append((x - 1, y))
            todo.append((x + 1, y))
            todo.append((x, y - 1))
            todo.append((x, y + 1))

Border Elimination

The algorithm first removes any land that is connected to the outer border. It iterates over the top and bottom rows, invoking fill with the water marker (0). The same is done for the leftmost and rightmost columns. Any land reachable from these edges is turned into water, guaranteeing that subsequent counting only sees islands fully enclosed by water.

for x in range(width):
    fill(x,          0, water)
    fill(x, height - 1, water)
for y in range(height):
    fill(0, y,         water)
    fill(width - 1, y, water)

Counting Closed Islands

After border elimination, the grid contains only isolated land cells marked with -1. The outer loops scan every cell; when a cell with the island marker is found, the counter count is incremented and a new unique identifier (the current count) is used to flood fill that entire island. The four neighbour calls around the discovered cell ensure that the whole region is labelled before the scan proceeds, preventing double counting.

count = 0
for y in range(height):
    for x in range(width):
        if grid[y][x] == island:
            count += 1
            fill(x - 1, y, count)
            fill(x + 1, y, count)
            fill(x, y - 1, count)
            fill(x, y + 1, count)

return count

Edge Cases Handled

The implementation gracefully handles islands that touch any side of the grid by converting them to water during the border elimination phase, ensuring they are never counted as closed islands. A grid that consists entirely of water becomes a uniform array of zeros after normalization, and the final counting loop finds no -1 cells, correctly returning zero. Conversely, a grid that is all land is first reduced to -1 everywhere; the border elimination then floods the entire perimeter and any connected interior, leaving no isolated region, again yielding a count of zero. Single-row or single-column grids are also covered because the border loops iterate over the only row or column, converting any land to water before the counting stage.

Performance Optimizations

The algorithm modifies the input grid in place, eliminating the need for auxiliary structures to track visited cells and thereby reducing memory overhead. The use of an explicit stack in fill avoids the overhead of recursive calls and prevents stack overflow on large inputs. By performing a single pass to eliminate border-connected land before any counting, the code ensures that the expensive flood-fill operation is only applied to truly closed islands, minimizing unnecessary work. Assigning a distinct integer identifier to each discovered island also allows the algorithm to skip already processed cells during the final scan, as those cells no longer match the island marker. These choices collectively keep the runtime efficient for dense or large grids.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big grid that looks like a map of the ocean. Some squares are water and some are land. An island is a group of land squares surrounded by water. A closed island is one that has water on every single side and does not touch the edge of the map.

First, the code looks at the whole map and changes all the numbers so it is easier to keep track of what is land and what is water. It marks all the land as a special spot to be checked later.

Next, it goes around the very outside edge of the map. If it finds any land touching the edge, it knows that land cannot be a closed island because it is not fully surrounded by water. It follows that land like a trail and turns it into water so it does not count anymore.

After the edges are cleared, the code looks at the rest of the map. It searches for any land that is still left. When it finds a piece of land, it realizes it has discovered a whole island. It gives this island a special name by counting it as one island and then finds all the parts connected to it. It does this over and over until every piece of land is either water or belongs to a specific closed island. Finally, the number of islands found is collected to show how many closed islands are hidden in the map.

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 | μ = 6.50 | σ = 1.74

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 Python
leetcode.ca C++ Java C# Python Go TS
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
suxrobGM C#
varunu28 Java
vthwang Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, TypeScript
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
varunu28 Java
vthwang Java
30 links | 17 authors | 7 languages

Videos

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

Solved On The Same Day

6 solutions   October 14, 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