LeetCode 200: Number of Islands is a Medium graph general problem. This Python walkthrough develops a grid flood fill solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Graph General |
| Reusable pattern | grid flood fill |
| Complexity | O(mn) time and O(mn) worst-case recursion space |
Recognizing the pattern
Graph traversal separates reachability from representation: adjacency describes possible moves, while a visited structure prevents repeated work.
For this problem specifically, when an unvisited land cell is found, count one island and flood-fill all orthogonally connected land. The invariant worth writing beside the code is: Every changed land cell belongs to the island currently being removed from future consideration.
Step-by-step algorithm
- Identify the input state consumed by
numIslands(grid)and initialize the data required by the grid flood fill pattern. - When an unvisited land cell is found, count one island and flood-fill all orthogonally connected land.
- After each update, verify the page’s central invariant: Every changed land cell belongs to the island currently being removed from future consideration.
- Finish only after the boundary behavior is covered: Only horizontal and vertical neighbors connect; an all-water grid returns zero.
Python solution
class Solution:
def numIslands(self, grid):
if not grid: return 0
rows, cols, islands = len(grid), len(grid[0]), 0
def flood(r, c):
if r < 0 or c < 0 or r == rows or c == cols or grid[r][c] != "1": return
grid[r][c] = "0"
flood(r + 1, c); flood(r - 1, c); flood(r, c + 1); flood(r, c - 1)
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1": islands += 1; flood(r, c)
return islandsReading the implementation
The main entry point is numIslands(grid). The named working state includes rows; those variables make the grid flood fill state visible instead of hiding it in incidental control flow.
The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, when an unvisited land cell is found, count one island and flood-fill all orthogonally connected land.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. When an unvisited land cell is found, count one island and flood-fill all orthogonally connected land. Each update records the current item without invalidating earlier decisions; consequently, every changed land cell belongs to the island currently being removed from future consideration.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(mn) time and O(mn) worst-case recursion space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
DFS and BFS often have the same asymptotic cost; choose DFS for recursive structure and BFS when distance or processing order matters. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
grid=[list("11000"),list("11000"),list("00100"),list("00011")]; assert Solution().numIslands(grid)==3Common mistakes and edge cases
- Problem-specific boundary: Only horizontal and vertical neighbors connect; an all-water grid returns zero.
- Pattern-level pitfall: Mark a state when it is discovered rather than after all of its neighbors are processed, or cycles can enqueue it repeatedly.
- Invariant check: after every update, confirm that every changed land cell belongs to the island currently being removed from future consideration.
Interview review checklist
- Explain why grid flood fill matches the structure of this input.
- State the invariant in one sentence before tracing code: Every changed land cell belongs to the island currently being removed from future consideration.
- Derive O(mn) time and O(mn) worst-case recursion space from how many times each element or state is visited.
- Test the boundary explicitly: Only horizontal and vertical neighbors connect; an all-water grid returns zero.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 98. Validate Binary Search Tree · Next: 130. Surrounded Regions