LeetCode 200: Number of Islands — Python Solution

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.

DifficultyMedium
TopicGraph General
Reusable patterngrid flood fill
ComplexityO(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

  1. When an unvisited land cell is found, count one island and flood-fill all orthogonally connected land.
  2. Maintain this invariant: Every changed land cell belongs to the island currently being removed from future consideration.
  3. 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 islands

Why 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