Graphs

LeetCode 200

LeetCode #200Difficulty: MediumNeetCode 150

LeetCode 200: Number of Islands

LeetCode

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

Problem Description

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

Examples:
Input: grid = [['1','1','0'],['1','1','0'],['0','0','1']]
Output: 2
Constraints:
  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300

Core Mental Model

Iterate through cells. When encountering '1', increment island count and trigger a DFS flood fill to sink all connected land cells to '0'.

Formal Loop Invariant

Invariant: Each connected component of '1's is visited exactly once by flood fill.

Key Architectural Takeaway:

Grid traversal can sink visited cells in-place to achieve O(1) auxiliary space without a visited matrix.

Asymptotic Complexity Analysis

Time ComplexityO(M * N)Linear scan
Space ComplexityO(M * N) recursion stack in worst-case.Constant auxiliary

Bottleneck: Visits each cell at most twice.

Edge Cases & Screener Traps

  • All water
  • All land