Solve LeetCode 200: Number of Islands in Python with a grid flood fill approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete 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 |
What the problem is testing
When an unvisited land cell is found, count one island and flood-fill all orthogonally connected land.
Algorithm
- When an unvisited land cell is found, count one island and flood-fill all orthogonally connected land.
- Maintain this invariant: Every changed land cell belongs to the island currently being removed from future consideration.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
from collections import Counter, defaultdict, deque, OrderedDict
import random
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 islandsWhy this is correct
The proof follows the maintained state: Every changed land cell belongs to the island currently being removed from future consideration. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O(mn) time and O(mn) worst-case recursion space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
Only horizontal and vertical neighbors connect; an all-water grid returns zero.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 98. Validate Binary Search Tree · Next: 130. Surrounded Regions