Number of Islands0/59 done
Part 2 · Problems · Grids and graphs

Number of Islands

#200 · Medium · LeetCode

Grid of '1' (land) and '0' (water). Count groups of land connected up, down, left, right.

4x5 grid with three separate land groups -> 3

Ask before coding

Hint

Every time you find unvisited land, that's a new island. Then sink the whole island.

Approach

Scan every cell. On a '1', count an island and flood fill it with DFS (stack), turning connected land to '0' so it's never counted again.

Time O(rows · cols)   Space O(rows · cols) worst case

Watch it run
Solution (JavaScript, tested)
function numIslands(grid) {
  const rows = grid.length,
    cols = grid[0]?.length ?? 0;
  let islands = 0;
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] !== "1") continue;
      islands++;
      const stack = [[r, c]];
      grid[r][c] = "0"; // mark visited when pushed
      while (stack.length) {
        const [y, x] = stack.pop();
        for (const [dy, dx] of [
          [1, 0],
          [-1, 0],
          [0, 1],
          [0, -1]
        ]) {
          const ny = y + dy,
            nx = x + dx;
          if (ny >= 0 && ny < rows && nx >= 0 && nx < cols && grid[ny][nx] === "1") {
            grid[ny][nx] = "0";
            stack.push([ny, nx]);
          }
        }
      }
    }
  }
  return islands;
}

Traps

Say out loud: Each land cell is a node with up to 4 neighbours. Counting islands is counting connected components.