Count Islands in a Grid

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

You are given a rectangular 2D matrix grid whose entries are single-character strings: "1" denotes dry land and "0" denotes open water. Everything outside the boundaries of the matrix is treated as water.

Two land cells belong to the same island whenever they share a horizontal or vertical edge (up, down, left, or right). Cells that meet only at a diagonal corner do not connect directly. An island is a maximal connected group of "1" cells.

Implement num_islands(grid) to return the total number of distinct islands in grid:

def num_islands(grid: List[List[str]]) -> int:

Use an iterative breadth-first search (BFS) traversal so deep or winding landmasses cannot exceed Python's call-stack limit, and handle empty-matrix corner cases ([] and [[]]) cleanly by returning 0.

Examples

Example 1

Input:
grid = [
  ["1", "0", "1", "1"],
  ["1", "0", "1", "0"],
  ["1", "1", "1", "0"]
]
Output: 1

Every "1" cell belongs to a single U-shaped landmass: the left column (0, 0) -> (1, 0) -> (2, 0) connects across the bottom row to (2, 2), rises up column 2 to (0, 2), and extends right to (0, 3).

Example 2

Input:
grid = [
  ["1", "1", "0", "0"],
  ["0", "1", "0", "1"],
  ["0", "0", "1", "0"],
  ["0", "0", "1", "1"]
]
Output: 3

There are three separate islands: {(0, 0), (0, 1), (1, 1)} in the upper-left, the isolated cell {(1, 3)} on the right edge, and {(2, 2), (3, 2), (3, 3)} near the bottom-right. Although (2, 2) touches both (1, 1) and (1, 3) diagonally, corner contact does not merge islands.

Constraints

  • 0 <= len(grid) <= 300
  • 0 <= len(grid[r]) <= 300, and all rows in grid have the same length
  • Each entry grid[r][c] is either "0" or "1"

Step-by-step walkthrough

  1. Understand the grid and island rules

    We are given a 2D grid of strings '1' (land) and '0' (water) and asked to count how many islands it contains, using breadth-first search (BFS) and handling every corner case cleanly.

    Before writing code, lock down the exact rules: - 4-directional connection only: Two '1' cells belong to the same island if they share an edge up, down, left, or right. Touching only diagonally ([['1', '0'], ['0', '1']]) forms 2 separate islands. - Strings, not integers: Every cell holds '1' or '0', not 1 or 0 ('1' == 1 is False in Python!). - Out-of-bounds is water: Everything outside 0 .. rows - 1 and 0 .. cols - 1 is water (the grid does not wrap around at edges). - Empty inputs: [] and [[]] contain 0 islands. - Preserving the caller's input: Overwriting '1' with '0' works, but mutates grid; using a separate seen boolean matrix keeps the input untouched.

  2. Key idea: scan and flood-fill each island once

    Think of land cells as nodes connected to their up/down/left/right land neighbors. Each island is one connected component (a maximal group of linked land cells).

    Why can't we just scan top-to-bottom, left-to-right and count every '1' that has water above it and to its left? Because an island can curve like a U:

    1  0  1   <-- top-left '1' and top-right '1' both look like "new" starts...
    1  0  1
    1  1  1   <-- ...until the bottom row connects them into ONE island!
    

    Instead, we combine a grid scan with a flood fill (spreading out from one starting cell across all connected land cells in all four directions): 1. Scan every (r, c) in the grid. 2. Skip water ('0') and already-visited land (seen[r][c] == True). 3. Whenever we hit an unvisited '1', increment islands += 1 and immediately flood-fill its entire connected island (moving down, up, right, and left) so none of its remaining cells will ever start a second count.

  3. Why BFS beats recursive DFS on large grids

    There are two standard ways to run a flood fill: - Recursive depth-first search (DFS) calls a function on each neighbor. On a 200 x 200 all-land grid (40,000 connected cells), recursion can go 40,000 frames deep — crashing past Python's default recursion limit of 1,000 (RecursionError). - Breadth-first search (BFS) uses a collections.deque (a double-ended queue with O(1) append at the back and O(1) popleft from the front) to explore neighbors wave by wave in plain loops, so recursion depth is zero.

    One BFS rule is critical: mark seen[next_r][next_c] = True at the moment you append a cell to the queue, NOT when you popleft it later! Watch what happens on a tiny 2 x 2 all-land grid if you wait until popleft to mark seen:

    1  1
    1  1
    
    Pop (0, 0) -> enqueues (1, 0) and (0, 1).
    Queue is [(1, 0), (0, 1)], and (1, 1) is STILL unmarked:
      - Pop (1, 0) -> sees (1, 1) unmarked -> enqueues (1, 1)
      - Pop (0, 1) -> STILL sees (1, 1) unmarked -> enqueues (1, 1) AGAIN!
    

    Across larger grids, duplicate pushes snowball exponentially unless prevented. Marking seen before queue.append(...) guarantees every land cell enters the queue at most once.

  4. Implement the BFS helper mark_island

    Notice how we check 0 <= next_r < rows and 0 <= next_c < cols before indexing grid[next_r][next_c]. In Python, grid[-1] is valid syntax for the last row — without 0 <= next_r, stepping up from row 0 would silently wrap around to row rows - 1!

    from collections import deque
    from typing import List
    
    # Four orthogonal step offsets (row_delta, col_delta): down, up, right, left.
    # Diagonal neighbors are omitted because corner-touching land does not connect.
    DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1))
    
    
    def mark_island(
        grid: List[List[str]], seen: List[List[bool]], start_r: int, start_c: int
    ) -> None:
        """Breadth-first search from (start_r, start_c) marking every cell in this island."""
        rows = len(grid)
        cols = len(grid[0])
    
        # queue: FIFO deque of (row, col) land cells whose 4 neighbors still need checking.
        seen[start_r][start_c] = True
        queue = deque([(start_r, start_c)])
    
        while queue:
            r, c = queue.popleft()
            for dr, dc in DIRECTIONS:
                next_r = r + dr
                next_c = c + dc
                # Check bounds BEFORE indexing grid: in Python, grid[-1] wraps to the last row!
                in_bounds = 0 <= next_r < rows and 0 <= next_c < cols
                if not in_bounds:
                    continue
                if grid[next_r][next_c] == "1" and not seen[next_r][next_c]:
                    # Mark as seen BEFORE enqueueing so two neighbors cannot push duplicate
                    # copies of (next_r, next_c), which would otherwise blow up the queue.
                    seen[next_r][next_c] = True
                    queue.append((next_r, next_c))
    
  5. Implement the outer scan num_islands

    Checking if not grid or not grid[0]: return 0 up front handles both [] and [[]]:

    from typing import List
    
    
    def num_islands(grid: List[List[str]]) -> int:
        # Handle empty corner cases: [] (zero rows) and [[]] (zero columns).
        if not grid or not grid[0]:
            return 0
    
        rows = len(grid)
        cols = len(grid[0])
        # seen: rows x cols boolean matrix tracking visited land without mutating `grid`.
        # Mini-shape for 2x2: [[True, False], [False, False]]
        seen = [[False] * cols for _ in range(rows)]
        islands = 0
    
        # Scan every cell; each unvisited '1' discovers a brand-new island and flood-fills it.
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == "1" and not seen[r][c]:
                    islands += 1
                    mark_island(grid, seen, r, c)
    
        return islands
    
  6. Walk through Example 2

    Grid:
      col:  0 1 2 3
    row 0:  1 1 0 0
    row 1:  0 1 0 1
    row 2:  0 0 1 0
    row 3:  0 0 1 1
    
    1. Scan hits (0, 0) == '1' (unseen) -> islands = 1
       BFS queue trace:
         start [(0,0)] -> pop (0,0), mark & push (0,1)
         pop (0,1)     -> mark & push (1,1)
         pop (1,1)     -> orthogonal neighbors are seen or '0' ((2,2) is diagonal, so ignored!)
       Island #1 marks {(0,0), (0,1), (1,1)}.
    
    2. Scan skips seen cells and '0's until (1, 3) == '1' (unseen) -> islands = 2
       BFS marks {(1,3)}; all 4 orthogonal neighbors are '0' or out of bounds.
    
    3. Scan continues to (2, 2) == '1' (unseen) -> islands = 3
       BFS marks {(2,2), (3,2), (3,3)}. Later scan positions (3, 2) and (3, 3) are already seen.
    
    Final answer: 3
    
  7. Full solution

    from collections import deque
    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Four orthogonal step offsets (row_delta, col_delta): down, up, right, left.
    # Diagonal neighbors are omitted because corner-touching land does not connect.
    DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1))
    
    
    def mark_island(
        grid: List[List[str]], seen: List[List[bool]], start_r: int, start_c: int
    ) -> None:
        """Breadth-first search from (start_r, start_c) marking every cell in this island."""
        rows = len(grid)
        cols = len(grid[0])
    
        # queue: FIFO deque of (row, col) land cells whose 4 neighbors still need checking.
        seen[start_r][start_c] = True
        queue = deque([(start_r, start_c)])
    
        while queue:
            r, c = queue.popleft()
            for dr, dc in DIRECTIONS:
                next_r = r + dr
                next_c = c + dc
                # Check bounds BEFORE indexing grid: in Python, grid[-1] wraps to the last row!
                in_bounds = 0 <= next_r < rows and 0 <= next_c < cols
                if not in_bounds:
                    continue
                if grid[next_r][next_c] == "1" and not seen[next_r][next_c]:
                    # Mark as seen BEFORE enqueueing so two neighbors cannot push duplicate
                    # copies of (next_r, next_c), which would otherwise blow up the queue.
                    seen[next_r][next_c] = True
                    queue.append((next_r, next_c))
    
    
    def num_islands(grid: List[List[str]]) -> int:
        # Handle empty corner cases: [] (zero rows) and [[]] (zero columns).
        if not grid or not grid[0]:
            return 0
    
        rows = len(grid)
        cols = len(grid[0])
        # seen: rows x cols boolean matrix tracking visited land without mutating `grid`.
        # Mini-shape for 2x2: [[True, False], [False, False]]
        seen = [[False] * cols for _ in range(rows)]
        islands = 0
    
        # Scan every cell; each unvisited '1' discovers a brand-new island and flood-fills it.
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == "1" and not seen[r][c]:
                    islands += 1
                    mark_island(grid, seen, r, c)
    
        return islands
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a map of '1' (land) tiles and '0' (water) tiles: as you scan across the map tile by tile, every time you land on an unpainted '1' tile, you add 1 to your island count and pour paint that spreads up, down, left, and right across every connected '1' tile until water stops it. Each island is a connected component (a maximal group of land tiles linked by valid steps), spreading paint across it is called a flood fill, and we run that spread using breadth-first search (BFS) — exploring connected tiles wave by wave with a first-in, first-out queue (collections.deque, a double-ended queue with O(1) appends at the back and pops from the front).

Simply counting '1' tiles that have '0' above and to their left fails whenever a U-shaped island has two separate northern tips that merge lower down. Using recursive depth-first search (DFS) — diving down one path via nested function calls before backtracking — visits the right cells on small grids, but on a 200 x 200 all-land grid (40,000 connected cells) it blows past Python's ~1,000-call stack limit with RecursionError. Iterative BFS uses zero recursion and visits every cell cleanly.

Walk through a tiny 2 x 3 example [['1', '1', '0'], ['1', '0', '1']]: 1. (0, 0) is an unseen '1': islands becomes 1, and BFS marks (0, 0) and enqueues [(0, 0)]. 2. Popping (0, 0) marks and enqueues (1, 0) and (0, 1); popping (1, 0) and (0, 1) finds no further unseen '1' neighbors ((1, 2) is separated by '0'). 3. The outer scan skips (0, 1) (seen), (0, 2) ('0'), (1, 0) (seen), and (1, 1) ('0'), then hits (1, 2) (unseen '1'), setting islands = 2 and returning 2.

Complexity

Let m be the number of rows and n be the number of columns.

  • Time — O(m * n): The outer loops inspect each of the m * n cells once, and because we mark seen before enqueueing, each land cell enters and leaves the deque at most once and checks at most 4 neighbors (O(1) work per cell).
  • Space — O(m * n): The seen boolean matrix stores m * n entries, and the BFS queue holds only the active frontier of one island at a time (at most O(min(m, n)) on a single rectangular flood wave, and never more than m * n cells in any shape).

Edge cases

  • Empty grids ([] and [[]]): if not grid or not grid[0]: return 0 returns 0 before indexing grid[0][0].
  • All water or all land: All '0's never triggers mark_island (0 islands); all '1's triggers mark_island once at (0, 0) and marks the entire m x n grid (1 island, even at 200 x 200).
  • Single-cell grids: [['1']] returns 1; [['0']] returns 0.
  • Diagonal-only neighbors ([['1', '0'], ['0', '1']]): Returns 2; a 5 x 5 checkerboard with '1' on the corners has 13 islands (ceil(m * n / 2) is the theoretical maximum).
  • Ring island enclosing an inner lake island: Water inside a ring does not split the ring, and a '1' inside that lake is counted separately (2 islands total).
  • Winding U- or spiral-shaped islands: Trying all 4 directions ((-1, 0) up and (0, -1) left included, not just right and down) ensures backward-curving arms are reached.
  • Opposite-edge cells ([['1', '0', '0', '1']]): Explicit 0 <= next_r < rows and 0 <= next_c < cols guards prevent wrapping across borders.

Common mistakes

  • Comparing with integer 1 instead of string '1': grid[r][c] == 1 is always False when cells are strings, silently returning 0 on every input.
  • Indexing grid[next_r][next_c] before checking next_r >= 0 and next_c >= 0: In Python, grid[-1] reads the last row instead of raising IndexError, falsely connecting the top edge to the bottom edge and the left edge to the right edge!
  • Marking seen on popleft() instead of append(): Waiting until removal lets multiple neighbors push duplicate copies of the same cell into the queue — without a second seen check on pop, duplicates cascade exponentially (C(r + c, r) copies at (r, c) on an all-land grid!).
  • Recursive DFS on large grids: Hits RecursionError when an island has more than ~1,000 cells.
  • Mutating grid in place (grid[r][c] = '0') unannounced: Saves the seen array (O(min(m, n)) BFS queue space), which is great if the caller allows destroying grid — always ask in an interview before mutating inputs.

Alternative approaches

  • Iterative DFS with a Python list stack: Replace deque and popleft() with a plain list and pop(). It visits the exact same connected component in O(m * n) time without recursion, though peak stack size can reach O(m * n) even on an all-'1' rectangle (whereas BFS's diagonal wave frontier stays O(min(m, n))).
  • In-place sinking (grid[r][c] = '0'): Overwriting visited '1's with '0' eliminates the O(m * n) seen matrix, reducing extra memory to O(min(m, n)) for the BFS frontier queue when mutating grid is permitted.
  • Union-Find (Disjoint-Set Union): A union-find data structure tracks a collection of non-overlapping sets supporting find(x) (which group does x belong to?) and union(x, y) (merge two groups). Initialize count to the number of '1' cells, merge each '1' with its right and down '1' neighbors, and decrement count on each successful merge — near-O(m * n) time and ideal when land arrives dynamically.

Follow-up questions

  • If the map starts completely submerged and land coordinates arrive one by one, how can you report the island count after each addition? Re-running BFS from scratch on every addition would cost O(k * m * n) across k additions. Instead, use union-find with path compression (making nodes along a find chain point higher up toward their set's root so future lookups stay nearly flat): each new land cell increments count by 1 and checks its 4 neighbors, merging any distinct adjacent island sets and decrementing count by 1 per merge in nearly O(1) amortized time per addition.
def num_islands_online(positions):
    parent = {}

    def find(cell):
        while parent[cell] != cell:
            parent[cell] = parent[parent[cell]]  # path halving
            cell = parent[cell]
        return cell

    count = 0
    history = []
    for r, c in positions:
        if (r, c) not in parent:
            parent[(r, c)] = (r, c)
            count += 1
            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                nb = (r + dr, c + dc)
                if nb in parent:
                    root_a, root_b = find((r, c)), find(nb)
                    if root_a != root_b:
                        parent[root_a] = root_b
                        count -= 1
        history.append(count)
    return history
  • What changes if diagonal neighbors also connect land cells (8-directional adjacency)? Simply add the four diagonal offsets ((1, 1), (1, -1), (-1, 1), (-1, -1)) to DIRECTIONS; the BFS queue, bounds check, seen marking, and O(m * n) time and space bounds stay identical (with 8 neighbor checks per cell instead of 4).
  • How would you count islands when the matrix has millions of rows streamed from disk one row at a time? You only ever need connectivity along the boundary of the previous row (O(n) memory for n columns). Assign component IDs to contiguous '1' runs in the incoming row (+1 island per run), use union-find over the active row labels whenever a '1' touches a '1' directly above it in the previous row (-1 island whenever two distinct component IDs merge), and compact/relabel only the surviving IDs present in the current row before reading the next row.

Follow-up questions

Similar questions

More Bloomberg interview questions

All 47 Bloomberg questions →