Skip to content
Decoder

Number of Islands

Medium

Problem

You get a map as a grid of strings: "1" is land and "0" is water. Land cells that touch **up, down, left or right** belong to the same island (diagonals do not count). Return how many islands there are.

Example 1

[["1","1","0","0"],

Example 2

 ["1","0","0","1"],

Example 3

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

Example 4

[["1","0"],

Example 5

Input
["0","1"]]
Output
2
Why
diagonal cells are separate

Constraints

  • 0 <= grid.length <= 300 and every row has the same length, at most 300
  • grid[i][j] is "0" or "1"
  • You may change the grid while you work.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.