Number of Islands in Python: BFS and DFS Explained

Grid with two differently colored islands; diagonal land cells do not connect.

Given a rectangular grid of strings ‘1’ (land) and ‘0’ (water), return the number of connected land components. Only horizontal and vertical neighbors connect. This medium-level graph problem treats each land cell as a vertex and each valid neighbor as an edge.

Example

Rows 110,010,001 contain two islands.

Pattern recognition and hints

Hint 1: Scan every cell; water never starts an island.

Hint 2: From an unvisited land cell, explore every reachable land neighbor.

Hint 3: Mark cells when discovered, not after processing them. Count each new traversal once.

Recursive DFS baseline

def dfs_count(grid):
    g = [row[:] for row in grid]
    def visit(r,c):
        if not (0 <= r < len(g) and 0 <= c < len(g[0])) or g[r][c] != "1":
            return
        g[r][c] = "0"
        for dr,dc in ((1,0),(-1,0),(0,1),(0,-1)):
            visit(r+dr,c+dc)
    count = 0
    for r,row in enumerate(g):
        for c,v in enumerate(row):
            if v == "1":
                count += 1
                visit(r,c)
    return count

Recursive DFS is already asymptotically optimal. It copies the grid and marks visited cells as water, preserving the caller’s input. Its drawback is Python’s recursion depth on long connected components.

Optimized or iterative approach

Every unvisited land cell starts a new traversal; mark the entire connected component.

from collections import deque
def num_islands(grid):
    if not grid or not grid[0]:
        return 0
    rows, cols = len(grid), len(grid[0])
    seen = set()
    count = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] != "1" or (r,c) in seen:
                continue
            count += 1
            seen.add((r,c))
            q = deque([(r,c)])
            while q:
                x,y = q.popleft()
                for dx,dy in ((1,0),(-1,0),(0,1),(0,-1)):
                    a,b = x+dx,y+dy
                    if (0 <= a < rows and 0 <= b < cols
                        and grid[a][b] == "1" and (a,b) not in seen):
                        seen.add((a,b))
                        q.append((a,b))
    return count

Pseudocode

SET count = 0 and seen = empty set
FOR each cell:
  IF land and not seen:
    INCREMENT count
    MARK cell and enqueue it
    WHILE queue is not empty:
      DEQUEUE cell
      FOR each of its four neighbors:
        IF valid unvisited land:
          MARK neighbor and enqueue it
RETURN count

Step-by-step walkthrough

Start at (0,0), visit (0,1) and (1,1). Later (2,2) starts a second island. Diagonal contact does not connect them.

The example uses zero-based coordinates. The table shows each dequeued cell, the queue after exploring its neighbors, and the island count.

CellQueue after expansionCount
(0,0)[(0,1)]1
(0,1)[(1,1)]1
(1,1)[]1
(2,2)[]2

Correctness argument

Each BFS visits exactly the reachable land component. Marking on enqueue prevents duplicate work. The outer scan starts one BFS per component, so the count is exact.

Soundness: only valid adjacent land is enqueued, so traversal cannot leave its component. Completeness: every reachable cell has a path from the starting cell, and processing each predecessor discovers the next cell on that path. The outer scan therefore counts each component exactly once.

Complexity analysis

Both DFS and BFS take O(rows × cols) time and O(rows × cols) worst-case space. Recursive DFS may exceed Python recursion limits; iterative BFS avoids that issue.

Edge cases

Expected results: [] → 0; [[‘0’]] → 0; [[‘1’]] → 1; rows 11,11 → 1; rows 10,01 → 2. A long narrow connected grid is a useful stress test for recursion depth. Both implementations assume a rectangular grid.

Interview follow-ups

Why mark when enqueuing? To avoid repeated queue entries. Is DFS slower asymptotically? No. Can we mutate the input? Only if the contract permits it.

Can we use union-find? Yes. Union adjacent land cells and count distinct roots; useful when land is added dynamically.

Why is O(rows × cols) optimal? In the worst case, every cell must be inspected because any unseen cell could be an isolated island.

What if diagonals connect? Add the four diagonal offsets to the neighbor list; the example would then contain one island.

Practice and revision

Original problem · DSA Roadmap

Scroll to Top