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
Difficulty
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
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 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.
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.
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++ | 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++ |
Videos
Similar Problems
- problem 130: Surrounded Regions
- problem 286: Walls and Gates
- problem 305: Number of Islands II
- problem 317: Shortest Distance from All Buildings
- problem 323: Number of Connected Components in an Undirected Graph
- problem 419: Battleships in a Board
- problem 694: Number of Distinct Islands
- problem 695: Max Area of Island
- problem 733: Flood Fill
- problem 1905: Count Sub Islands
- problem 1992: Find All Groups of Farmland
- problem 2282: Number of People That Can Be Seen in a Grid
- problem 2316: Count Unreachable Pairs of Nodes in an Undirected Graph
- problem 2658: Maximum Number of Fish in a Grid
Solved On The Same Day
- problem 130: Surrounded Regions
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