Problem 200

Abstract / Summary

Count how many separate groups of connected land cells exist in a grid of water and land.

Note

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

Python 0200.py

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

        unknown = set()
        for x in range(width):
            for y in range(height):
                if grid[y][x] != "0":
                    unknown.add(tuple([ x, y ]))

        result = 0
        visited = set()
        while unknown:
            result += 1
            todo = set([ unknown.pop() ])
            while todo:
                cell = todo.pop()
                x, y = cell

                if grid[y][x] == "0":
                    continue

                if cell in visited:
                    continue
                visited.add(cell)
                unknown.discard(cell)

                if x > 0:
                    todo.add(tuple([ x - 1, y ]))
                if x < width - 1:
                    todo.add(tuple([ x + 1, y ]))
                if y > 0:
                    todo.add(tuple([ x, y - 1 ]))
                if y < height - 1:
                    todo.add(tuple([ x, y + 1 ]))

        return result
38 lines | 1116 bytes | submitted September 3, 2023 | GitHub   tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 65% (6+ million 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 provided Solution class implements a method numIslands that counts the number of distinct islands in a two-dimensional grid. An island is defined as a group of horizontally or vertically adjacent cells containing the character "1" (any non-zero value). The algorithm treats the grid as a graph where each land cell is a node and edges exist between orthogonal neighbors. It repeatedly extracts an unvisited land cell, performs a flood-fill traversal to mark all cells belonging to the same island, and increments a counter. The traversal uses explicit sets to manage unknown, visited, and pending cells, avoiding recursion and thereby preventing stack overflow on large inputs.

Key Steps

Determining Grid Dimensions

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

The code extracts the number of columns (width) and rows (height) once at the start, allowing constant-time boundary checks later in the algorithm.

Building the Set of Unexplored Land Cells

unknown = set()
for x in range(width):
    for y in range(height):
        if grid[y][x] != "0":
            unknown.add(tuple([ x, y ]))

A double loop iterates over every coordinate. Whenever a cell is not "0" it is added to the unknown set as a tuple (x, y). This set represents all land cells that have not yet been assigned to an island. By storing coordinates as immutable tuples, the set operations (add, discard, pop) are O(1) on average.

Main Loop Over Islands

result = 0
visited = set()
while unknown:
    result += 1
    todo = set([ unknown.pop() ])
    ...

The outer while loop continues until unknown is empty. Each iteration corresponds to discovering a new island, so the result counter is incremented. A new todo set is seeded with a single cell removed from unknown. This cell becomes the starting point for a flood-fill that will consume the entire island.

Flood-Fill Traversal

while todo:
    cell = todo.pop()
    x, y = cell

    if grid[y][x] == "0":
        continue

    if cell in visited:
        continue
    visited.add(cell)
    unknown.discard(cell)

    if x > 0:
        todo.add(tuple([ x - 1, y ]))
    if x < width - 1:
        todo.add(tuple([ x + 1, y ]))
    if y > 0:
        todo.add(tuple([ x, y - 1 ]))
    if y < height - 1:
        todo.add(tuple([ x, y + 1 ]))

Inside the inner while loop, the algorithm repeatedly extracts a cell from todo. The first guard discards any water cell that might have been added inadvertently. The second guard skips cells already processed, ensuring each land cell is visited exactly once. After marking the cell as visited, it is removed from unknown to keep the two sets consistent.

The four conditional blocks generate neighbor coordinates only when they lie inside the grid bounds. Each valid neighbor is added to todo regardless of its current state; subsequent guards will filter out water or already visited cells. This approach simplifies neighbor handling and guarantees that all reachable land cells are eventually explored.

Returning the Count

return result

When unknown becomes empty, every land cell has been assigned to an island, and the accumulated result value is returned.

Edge Cases Handled

The algorithm gracefully handles an empty grid by relying on the assumption that grid[0] exists; however, when the grid contains rows but no columns, the loops simply never add any cell to unknown, and the final count remains zero.

If the grid consists entirely of water ("0"), the initial population of unknown yields an empty set, causing the outer while loop to be skipped and the method to return zero islands.

When islands touch the grid borders, the boundary checks (x > 0, x < width - 1, y > 0, y < height - 1) prevent attempts to access out-of-range indices, thereby avoiding index errors.

The use of a visited set ensures that cells that belong to multiple neighboring islands (which cannot happen in a correct input) are not double-counted; the guard if cell in visited stops redundant processing.

Performance Optimizations Observed

The code avoids recursion entirely, using explicit sets for both the frontier (todo) and the collection of unprocessed land cells (unknown). This eliminates the risk of hitting Python’s recursion limit on large grids and reduces overhead associated with function calls.

By storing coordinates as tuples, the algorithm leverages the highly optimized hash-based lookup of Python sets, making membership tests (in visited, discard, pop) fast.

The unknown set is progressively shrunk via discard inside the flood-fill, which means that the outer loop’s termination condition (while unknown) becomes cheaper as the algorithm proceeds, because the set size diminishes.

Neighbor generation is performed only when the current cell is confirmed to be land and not previously visited, preventing unnecessary addition of water cells to the frontier.

The separation of visited and unknown allows the algorithm to quickly check whether a cell still needs processing without scanning the entire grid again.

Overall, the design emphasizes constant-time set operations and minimizes repeated work, resulting in an efficient traversal even for dense or irregular island configurations.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a giant map made of little squares that are either empty ocean or pieces of land. The computer looks at this map to count how many separate islands are hiding there.

First, the code walks through the whole map to find every single piece of land and puts them all into a big pile called unknown. This pile keeps track of all the dirt that has not been explored yet.

Once the computer finds a piece of land in the pile, it knows an island has started. It picks up that piece of land and looks at its neighbors to see if they are also land. If a neighbor is land, it gets added to a special list called todo to be checked next. The computer keeps jumping to all the connected land pieces, one after another, to explore the whole island. It remembers which pieces it has already seen so it does not get confused or count the same island twice.

The computer keeps doing this until every piece of land in the big pile has been visited. Every time a new search starts because it finds a piece of land that was not part of the previous island, it means a brand new island has been discovered.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.96 | σ = 1.10

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++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
fsq Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
fsq Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
61 links | 45 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Count Number of Islands using Graphs | Data Structure and Algorithms'
Pepcoding 17 mins
Count Number of Islands using Graphs | Data Structure and Algorithms
YouTube video 'Technical Interview Question: Number of Islands [LeetCode]'
AlgosWithMichael 18 mins
Technical Interview Question: Number of Islands [LeetCode]
YouTube video 'Number of Islands (LeetCode 200) | Full solution with a DFS and a BFS approach'
Nikhil Lohia 21 mins
Number of Islands (LeetCode 200) | Full solution with a DFS and a BFS approach
YouTube video 'Number of Islands | DFS | BFS |  Same as Island Perimeter | Leetcode 200 | codestorywithMIK'
codestorywithMIK 18 mins
Number of Islands | DFS | BFS | Same as Island Perimeter | Leetcode 200 | codestorywithMIK
YouTube video 'Number of Islands - Breadth First Search (LeetCode)'
AlgosWithMichael 15 mins
Number of Islands - Breadth First Search (LeetCode)
YouTube video 'Number of Islands - LeetCode 200 Python'
Deepti Talesra 13 mins
Number of Islands - LeetCode 200 Python
YouTube video 'Number of Islands - LeetCode 200 - JavaScript'
AlgoJS 11 mins
Number of Islands - LeetCode 200 - JavaScript
YouTube video 'LeetCode 30 day Challenge | Day 17 | Number of Islands (C++, Java, Python) | LeetCode 200'
Knowledge Center 25 mins
LeetCode 30 day Challenge | Day 17 | Number of Islands (C++, Java, Python) | LeetCode 200
YouTube video 'Number of Islands - LeetCode 200 - Coding Interview Questions'
One Code Man 4 mins
Number of Islands - LeetCode 200 - Coding Interview Questions
YouTube video '[Java] Leetcode 200. Number of Islands [Search #1]'
Eric Programming 9 mins
[Java] Leetcode 200. Number of Islands [Search #1]
YouTube video '200. Number of Islands || Java || Leetcode || Hindi'
Coding Sphere 6 mins
200. Number of Islands || Java || Leetcode || Hindi
YouTube video 'number of islands leetcode | leetcode 200 | dfs | bfs | google microsoft'
Naresh Gupta 12 mins
number of islands leetcode | leetcode 200 | dfs | bfs | google microsoft
YouTube video 'G-12 Number of Islands I Day008 | Number of Connected Components I Leetcode 200 I C++/Java'
Aryan Mittal 15 mins
G-12 Number of Islands I Day008 | Number of Connected Components I Leetcode 200 I C++/Java
YouTube video 'Amazon Coding Interview Question | Leetcode 200 | Number of Islands'
WorkWithGoogler 15 mins
Amazon Coding Interview Question | Leetcode 200 | Number of Islands
YouTube video 'Number Of Islands - 200. LeetCode - Java'
Teddy Smith 9 mins
Number Of Islands - 200. LeetCode - Java
YouTube video '200. Number of Islands | JavaScript | LeetCode Daily Challenge | Matrix | Depth First Search | DFS'
LeetCodeWithMonu 17 mins
200. Number of Islands | JavaScript | LeetCode Daily Challenge | Matrix | Depth First Search | DFS
YouTube video 'Leetcode 200 | Number of Islands | DFS (Java Solution)'
The Tech Granth 14 mins
Leetcode 200 | Number of Islands | DFS (Java Solution)
YouTube video 'Number of Islands - Leetcode 200 | Animation | Visualization'
Depth First 10 mins
Number of Islands - Leetcode 200 | Animation | Visualization
YouTube video 'LeetCode 200: Number of Islands in Telugu | BFS Approach | Python DSA | SRKCodes'
Srk Codes 21 mins
LeetCode 200: Number of Islands in Telugu | BFS Approach | Python DSA | SRKCodes
YouTube video 'Number Of Islands || C++ || GFG Daily Problem'
CodeFreaks 19 mins
Number Of Islands || C++ || GFG Daily Problem
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

14 similar problems

Solved On The Same Day

1 medium
2 solutions   September 3, 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