iq.lab
Python starts when a code cell comes near or you run one
mediumDepth-first search target 25 min

Number of islands

A map is a grid of strings: "1" is land and "0" is water. Two land cells are on the same island when you can walk from one to the other by stepping up, down, left or right, only on land. Diagonal steps do not count. Everything outside the grid is water.

Return how many islands the map holds.

The cells are the strings "1" and "0", not the numbers 1 and 0, the same as on LeetCode. Compare with "1".

Example 1
Inputgrid = [["1", "1", "0", "0"], ["0", "1", "0", "1"], ["1", "0", "0", "1"]]Output3

The three land cells at the top left, the two on the right, and the single cell at the bottom left.

Example 2
Inputgrid = [["1", "0", "1"], ["0", "1", "0"], ["1", "0", "1"]]Output5

Each land cell touches the others only at corners, so each one is its own island.

Example 3
Inputgrid = [["0", "0"], ["0", "0"]]Output0

No land, no islands.

Constraints
  • 1 ≤ number of rows, number of columns ≤ 300

  • Every cell is "0" or "1".

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.