Number of Islands
Flood-fill each unseen land component and count how many independent searches begin.
Core idea
Scan the grid. Every unseen land cell starts one new component search, and that flood fill marks all land reachable through four-directional neighbors.
Read the visualization
The scan cursor moves row by row. A newly discovered island changes the traversal color, and the active frontier spreads until water or visited cells block it.
🔎
This unseen land cell starts a new island and a new flood fill.
1function numIslands(grid: number[][]): number {
2 const rows = grid.length, cols = grid[0].length;
3 let count = 0;
4 const flood = (r: number, c: number): void => {
5 if (r < 0 || r >= rows || c < 0 || c >= cols) return;
6 if (grid[r][c] === 0) return; // water / already visit
7 grid[r][c] = 0; // flood as already visit (flood)
8 flood(r - 1, c); flood(r + 1, c);
9 flood(r, c - 1); flood(r, c + 1);
10 };
11 for (let r = 0; r < rows; r++) {
12 for (let c = 0; c < cols; c++) {
13 if (grid[r][c] === 1) { // hit scan land
14 count++;
15 flood(r, c);
16 }
17 }
18 }
19 return count;
20}
grid4×4(1= land /0= water)
current cell(0,0)
island count1
counted land1
1 / 20
Complexity and tradeoffs
Time: O(RC). Space: O(RC). Every grid cell is visited at most once; iterative traversal can replace recursion.
Invariant: After a flood fill ends, every cell in that island is marked, so no later scan position can count it again.
Where it fits
Grid component labeling supports maps, image regions, board games, and cluster counting. Diagonal connectivity or weighted movement changes only the neighbor relation.