Number of Islands

35 min · numIslands()

A satellite sends you a blocky map: land is marked "1", water is marked "0". The useful question isn't how much land you see. It's how many separate land masses the map contains.

An island is one or more land cells connected through shared top, bottom, left, or right edges. Given grid, return its number of islands.

A few ground rules:

  • Diagonal contact doesn't join two islands.
  • Every cell is a single-character string: "1" for land or "0" for water.
  • The grid is rectangular, so every row has the same width.

Constraints

  • 1 <= grid.length <= 300
  • 1 <= grid[r].length <= 300
  • Every row has the same length.
  • grid[r][c] is either "0" or "1".

Hints

Find one shoreline

Scan the board. The first unvisited land cell you meet belongs to an island you haven't counted yet.

Consume the whole island

After counting that first cell, walk through all connected land. Mark each visited cell as water so the outer scan can't count the same island again.

Keep movement orthogonal

Your traversal has exactly four directions. Adding diagonals silently changes the meaning of an island and breaks checkerboard cases.

Follow-up

If you weren't allowed to modify grid, what extra structure would you use to remember the land cells you've already visited?

Visible cases

Examples

Example 1

ready
Input
grid = [
  [
    "1",
    "1",
    "0",
    "0",
    "0"
  ],
  [
    "1",
    "1",
    "0",
    "0",
    "0"
  ],
  [
    "0",
    "0",
    "1",
    "0",
    "0"
  ],
  [
    "0",
    "0",
    "0",
    "1",
    "1"
  ]
]
Expected
3
Why
the top-left block, center cell, and bottom-right pair are three islands

Example 2

ready
Input
grid = [
  [
    "1",
    "1",
    "1",
    "1",
    "0"
  ],
  [
    "1",
    "1",
    "0",
    "1",
    "0"
  ],
  [
    "1",
    "1",
    "0",
    "0",
    "0"
  ],
  [
    "0",
    "0",
    "0",
    "0",
    "0"
  ]
]
Expected
1
Why
every land cell connects back to the same large island

Example 3

ready
Input
grid = [
  [
    "1",
    "0",
    "1"
  ],
  [
    "0",
    "1",
    "0"
  ],
  [
    "1",
    "0",
    "1"
  ]
]
Expected
5
Why
diagonal land cells don't connect, so each one stands alone

Interview signal

Asked at

AmazonGoogleMetaBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite