Count the Islands

EasyGraphs≈ 20 min

A map is given as a list of equal-length strings, one per row: # is land and . is water. Land cells that touch up, down, left or right belong to the same island; cells that only touch diagonally do not.

Return the number of islands.

Examples

text
["##...",
 "##...",
 "..#..",
 "...##"]        →  3

["#####"]        →  1

["#.#",
 ".#.",
 "#.#"]          →  5

In the last example, no two land cells share a side, so each one is an island of its own.

Constraints

  • Up to 100 rows and 100 columns; the grid may be empty.
  • Aim for O(n) in the number of cells: visit each cell a constant number of times.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 3 visible cases here, in your browser. Submit runs all 7 on the judge, 4 of them hidden, and measures how your solution scales.