Number of Islands
Count islands in a grid of '1' (land) and '0' (water). Land connects 4-directionally.
Intuition
Every island is one connected component. Scan the grid; each time you step on unvisited land, that is a brand-new island — count it, then flood-fill (sink) the whole component so none of its cells can be counted again. The counter increments exactly once per island because the flood erases the rest of it.
Approach
Scan + sink
Loop over every cell. On seeing '1': answer += 1, then DFS from that cell turning every reachable '1' into '0' (or a visited mark).
The flood fill
DFS(r,c): if out of bounds or water, return. Set grid[r][c]='0', recurse into the 4 neighbors. Marking before recursing prevents infinite loops.
Why it counts correctly
The counter only fires on land that survived all previous floods — i.e. land in a component never seen before. One fire per component = number of islands.
Solution & live demo
Edge cases
Counter never fires — 0.
First cell fires, flood sinks everything — 1.
Diagonals are not connections; such islands count separately.