Treat a grid as a graph where each cell connects to its neighbours, and walk it with loops, DFS or BFS.
Used for
islands = 0
islands = 1
islands = 1
Cell (1,2) is land. Is the cell diagonally below-right of it, (2,3), a direct neighbour?
Not quite. Island problems connect cells that share an edge. (2,3) is reached through (2,2) instead.
Step 1 of 6
Goal: count the islands of 1s in this grid (0 is water). Treat the grid as a map where each cell touches its neighbours above, below, left and right. Scan the cells one by one.
Step 2 of 6
The first land cell we meet is row 1, column 2. A new island starts here.
Step 3 of 6
Spread out: look at its four neighbours. The cell below, row 2 column 2, is land too.
Step 4 of 6
Keep spreading from each new land cell: row 2 columns 1 and 3 join, then row 3 column 2.
Step 5 of 6
The whole island is found. Mark its cells as visited so the scan never counts them again. Answer: 1 island. Each cell is looked at a few times, so the work is rows × columns. This is matrix traversal.
Step 6 of 6
Your turn.
2D Arrays (Matrices)Unique Paths ProblemSquare Matrix In-Place RotationMatrices
function islands(grid) { let count = 0; const sink = (r, c) => { if (grid[r]?.[c] !== '1') return; grid[r][c] = '0'; sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1); }; grid.forEach((row, r) => row.forEach((v, c) => { if (v === '1') { count++; sink(r, c); } })); return count;}