Number of Islands — Graphs: BFS/DFS

Count the separate pieces of land on a coastal satellite grid of land and water cells, linked only through shared edges, not corners.

Graphs: BFS/DFS · Easy

The problem

You are a flood insurer reviewing a satellite map of a coastline. The map is a grid of "1" (land) and "0" (water). An island is a group of land cells that are linked through horizontal or vertical neighbours. Count the islands.

The story

After a hurricane, a flood insurer receives a satellite grid of a coastline, at most 8 by 8 cells, each marked land ("1") or water ("0"). Each separate island is one claims zone, and the insurer needs to know how many zones the map shows. Two land cells belong to the same island when they touch along a side; touching only at a corner doesn't count.

What to return

Constraints

Example

Input
grid = 1001 | 1100 | 0010
Output
3

Solve it

More in Graphs: BFS/DFS

All algorithm problems