Medium Matrices

Number of Islands

Receives a rectangular grid of integers, 0 for water and 1 for land, and returns how many islands it contains. An island is a maximal group of land cells connected horizontally or vertically, surrounded by water (the grid's four edges are treated as bordered by water). It scans the grid in row-major order and, whenever it finds an unvisited land cell, counts a new island and floods outward from it with a depth-first search that marks every land cell reachable through its four orthogonal neighbors as visited, so the outer scan never counts the same island twice. Returns the total number of islands found; an all-water grid returns 0.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References