Skip to problem
←

Number of Islands

Medium 0 attempts
Daily

Given a rectangular grid of string characters "1" (land) and "0" (water), return the number of separate islands.

Land cells belong to the same island when connected through up, down, left, or right steps. Diagonal contact does not connect islands. Treat the area outside the grid as water; land may still touch the grid’s boundary. An island containing a lake remains one island.

Count islands, not land cells. In Example 1, the three connected land cells at the upper left form one island; the bottom-right cell forms another, giving 2.

Function contract

Implement numIslands(grid). Receive a nonempty rectangular matrix of string characters "0" and "1". You may modify grid to mark visited cells.

Output: Return the number of separate four-directionally connected groups of land cells, not their area.

Example 1

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

Example 2

Input
grid = [["0"]]
Output
0
Visual Aid
Example 1: diagonal contact is separate
Three cells marked A form one island; a diagonally touching cell B is a second islandAA00A000BA: three connected cellsB: one separate cellReturn 2 islands0 = water

Letters label the two islands; every A or B cell is a "1" in the input.

Constraints
  • 1 <= m, n <= 300
  • grid[i][j] is '1' or '0'
Topics

Iterative Flood Fill

Each unvisited land cell starts a new island. Mark cells when they enter the stack so every land cell is processed once.

javascript
function numIslands(grid) {
  const rows = grid.length,
    cols = grid[0].length;
  let count = 0;
  for (let r = 0; r < rows; r++)
    for (let c = 0; c < cols; 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 [dx, dy] of [
          [1, 0],
          [-1, 0],
          [0, 1],
          [0, -1],
        ]) {
          const nx = x + dx,
            ny = y + dy;
          if (
            nx >= 0 &&
            nx < rows &&
            ny >= 0 &&
            ny < cols &&
            grid[nx][ny] === "1"
          ) {
            grid[nx][ny] = "0";
            stack.push([nx, ny]);
          }
        }
      }
    }
  return count;
}

Time: O(rows × cols) | Space: O(rows × cols)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript