Medium Count connected components of land in a 2-D grid.
Given an m × n grid of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and formed by connecting adjacent land cells horizontally or vertically.
Walkthrough boards: 3 islands one island scatter all water
click any cell to toggle land / water
1 function numIslands(grid) { 3 const sink = (r, c) => { 4 if (oob(r, c) || grid[r][c] !== '1') return; 6 sink(r+1,c); sink(r-1,c); sink(r,c+1); sink(r,c-1); 8 for (let r = 0; r < rows; r++) 9 for (let c = 0; c < cols; c++) 10 if (grid[r][c] === '1') { count++; sink(r, c); } count = 0
1 1 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 1 1
water (0) land (1) sunk → 0, colored by island scanning
STEP 0 / 31 · line 2
Start
Scan the grid row by row. Each unvisited land cell starts a new island, which we flood-fill.
Intuition Each island is a connected component of land cells. Counting islands = counting components.
Scan the grid; the first time you hit an unvisited land cell, you have found a new island.
Flood-fill (DFS) from that cell, sinking every connected land cell to water so it is not counted again.
The algorithm 01 Walk every cell (r, c) of the grid. 02 When you find a '1', increment the island count. 03 Run a DFS that sinks the cell and recurses into its four neighbours. 04 The sink marks land as water, so each island is counted exactly once. Reference implementation JavaScript TypeScript Python Java C++
copy 1 function numIslands(grid) { 2 if (!grid.length) return 0; 3 const rows = grid.length, cols = grid[0].length; 6 const sink = (r, c) => { 7 if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] !== '1') return; 8 grid[r][c] = '0'; // mark visited 15 for (let r = 0; r < rows; r++) { 16 for (let c = 0; c < cols; c++) { 17 if (grid[r][c] === '1') { Complexity Time
O(m · n) — every cell is visited a constant number of times.
Space
O(m · n) worst case for the recursion stack.