CodingNodes / Graphs / Number of Islands System design Space play · ←→ step · R restart

Problem

A map is a grid of characters: "1" is land and "0" is water.

An island is a group of land cells connected up, down, left or right. Cells that only touch diagonally are not connected.

Return how many islands the map has. You may change the grid while you work.

Constraints

  • 1 ≤ rows, cols ≤ 300
  • grid[r][c] is "0" or "1"

Examples: pick one to animate

Solutions

TimeO(rows · cols) SpaceO(rows · cols)

Time: The scan visits each cell once. Each land cell is sunk once, pushed once and popped once, and each pop checks 4 neighbors.

Space: In the worst case (all land) the stack can hold O(rows · cols) cells. An explicit stack avoids the deep recursion a big snake-shaped island would cause.

Scan the grid. When you meet land, count one island and sink the whole island (set every cell to 0) so it is never counted again. To sink it, keep a stack: pop the newest cell and push its land neighbors. Sink each cell as you push it, so nothing is pushed twice.