Count Separate Land Masses in a Grid
Trees & GraphsAuto-graded · 18 test casesLast updated
Evaluate grid graph connectivity by finding the number of distinct 4-directionally connected land components.
Given a two-dimensional grid of characters representing a map, where '1' indicates land and '0' indicates open water, calculate the total number of distinct islands.
An island is defined as a maximal set of adjacent land cells connected orthogonally (up, down, left, right). Diagonal adjacencies are not considered connected.
Input consists of a list of string lists grid. You may mutate grid in-place if needed.
Constraints
m == len(grid)n == len(grid[i])1 <= m, n <= 300grid[i][j]is either'0'or'1'.
Examples
Example 1
Input: count_islands([['1', '1', '1', '1', '0'], ['1', '1', '0', '1', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '0', '0', '0']])
Output: 1
Example 2
Input: count_islands([['1', '1', '0', '0', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '1', '0', '0'], ['0', '0', '0', '1', '1']])
Output: 3
Example 3
Input: count_islands([['0', '0', '0'], ['0', '1', '0'], ['0', '0', '0']])
Output: 1
Hints
Hint 1
Model the grid as an unweighted, undirected graph where each '1' cell is a node and edges connect orthogonally adjacent '1' cells.
Hint 2
Traverse the grid sequentially. When you encounter an unvisited '1', increment your counter and run a BFS or DFS to visit and mark all reachable '1' cells.
Hint 3
To avoid stack overflow in Python on large landmasses, use an iterative traversal (queue or explicit stack) rather than direct recursion.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem asks us to find the number of connected components in an implicit graph defined by a 2D matrix.
- Iterate through every position in the grid sequentially.
- Detect new islands: When encountering a cell containing
'1', it represents a previously unvisited island. We increment our component counter. - Traverse the component: Run an iterative search—Depth-First Search (DFS) with a stack or Breadth-First Search (BFS) with a queue—to visit all land cells belonging to this component.
- Mark visited cells: Modify each visited land cell in-place by setting it to
'0'(or using a separatevisitedset if matrix mutation is prohibited). Overwriting visited cells prevents reprocessing them later during the outer grid iteration.
Using an iterative stack avoids exceeding Python's default recursion limit when processing large grid sizes (e.g., $300 \times 300$).
Complexity Analysis
- Time Complexity: $O(m \times n)$, where $m$ is the number of rows and $n$ is the number of columns. Every cell is visited by the main loop, and every land cell is pushed and popped from the traversal stack at most once.
- Space Complexity: $O(m \times n)$ in the worst-case scenario (e.g., a grid filled entirely with land cells) due to the call stack/queue storing unvisited neighbors.
from typing import List
def count_islands(grid: List[List[str]]) -> int:
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
islands = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != '1':
continue
islands += 1
grid[r][c] = '0'
stack = [(r, c)]
while stack:
cr, cc = stack.pop()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = cr + dr, cc + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == '1':
grid[nr][nc] = '0'
stack.append((nr, nc))
return islands