call(back)
Algorithms & Data StructuresmediumSign in to star problems

Number of Islands

Count the islands in a grid of '0' (water) and '1' (land). Land cells connect four-directionally — up, down, left, right — and an island is a maximal connected group of land. The grid arrives as a list of equal-length strings.

["11000",
 "11000",
 "00100",
 "00011"]   ->  3

Do not mutate the input.

Hints

Hint 1

Scan every cell; each unvisited land cell starts a new island, and a flood fill (iterative DFS with an explicit stack, or BFS with a queue) marks everything reachable from it as visited before the scan continues.

Hint 2

Recursive DFS risks a stack overflow on one huge island; an explicit stack or a queue does not. Union-find is the structure to name if islands can be added later — each successful union removes one component from a running count.

Asked at