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
- Return the number of islands as an integer.
- Cells that only touch diagonally are not connected.
- A grid with no land has 0 islands.
Constraints
- 1 <= rows, cols <= 8, and every row has the same length
- each cell is the string "0" or the string "1"
Example
- Input
grid = 1001 | 1100 | 0010- Output
3