sagelearnai

Number of Islands

Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #200

grid is a 2-D map of "1" (land) and "0" (water). An island is a group of land cells connected horizontally or vertically. Count the islands. Everything outside the grid is water.

Example

text
grid = [["1","1","0","0","0"],
        ["1","1","0","1","0"],
        ["0","0","1","0","0"],
        ["0","0","0","1","1"]]   →  4

Hints

  1. Every time you find land you haven't visited yet, you've found a new island.
  2. Then visit (flood) the whole island so you don't count it again.
  3. You can mark visited cells by overwriting them with "0".

Approach

Scan every cell. When you find a "1", increment the count and flood-fill from it (DFS or BFS), turning every connected land cell into "0". Each cell is visited a constant number of times, so O(R·C). Use iterative BFS/DFS for very large grids to avoid recursion limits. The visualizer above shows BFS flooding each island.

Complexity

Time: O(R·C). Space: O(R·C) worst case for the queue/stack.

Python solution
from collections import deque

def numIslands(grid):
    R, C = len(grid), len(grid[0])
    count = 0
    for r in range(R):
        for c in range(C):
            if grid[r][c] != "1":
                continue
            count += 1
            grid[r][c] = "0"
            q = deque([(r, c)])
            while q:
                x, y = q.popleft()
                for nx, ny in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
                    if 0 <= nx < R and 0 <= ny < C and grid[nx][ny] == "1":
                        grid[nx][ny] = "0"
                        q.append((nx, ny))
    return count
JavaScript solution
function numIslands(grid) {
  const R = grid.length, C = grid[0].length;
  let count = 0;
  for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) {
    if (grid[r][c] !== '1') continue;
    count++;
    grid[r][c] = '0';
    const stack = [[r, c]];
    while (stack.length) {
      const [x, y] = stack.pop();
      for (const [nx, ny] of [[x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]]) {
        if (nx >= 0 && ny >= 0 && nx < R && ny < C && grid[nx][ny] === '1') { grid[nx][ny] = '0'; stack.push([nx, ny]); }
      }
    }
  }
  return count;
}