Example 1
- Input
- grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
- Output
- 1
Every land cell touches another through shared sides, so the grid holds a single island.
Given a grid of land and water cells, count how many islands appear. Each island is a group of land cells joined horizontally or vertically.
Given a rectangular grid of characters "1" (land) and "0" (water), return the number of islands.
Two land cells belong to the same island if a path of land cells joins them using only up, down, left and right moves. Diagonal contact does not connect islands. Treat the grid boundary as surrounded by water.
m == grid.length and n == grid[i].length; all rows have the same length."0" or "1".Every land cell touches another through shared sides, so the grid holds a single island.
The top-left four cells form one island. The cell (2, 2) is a second, and (3, 3) with (3, 4) is a third. Although (2, 2) and (3, 3) meet diagonally, no shared side joins them, so the answer is 3.
The smallest allowed grid contains only water. There is no starting land cell, so no traversal begins and the answer is 0.
A single land cell needs no land neighbours to form an island. The scan counts it once and its traversal immediately finishes.
Think of each land cell as a graph vertex and each shared side between land cells as an edge. An island is one connected component: all cells reachable from one starting land cell. In Example 1, the nine land cells are reachable from (0, 0), even though some are far away in the row scan. Count a component only when the scan finds unclaimed land, then claim every reachable cell before continuing. A separate visited grid preserves the input; changing land to water uses the input itself as the visited record.
Reveal BFS With Visited: intuition, complexity, and code
To count connected components, scan for unclaimed vertices, start one traversal per fresh vertex, and mark every reachable vertex before continuing. Grid side-adjacency supplies the graph edges. A visited structure preserves the map; mutation can replace those marks but does not remove traversal memory.