LeetCode #200

Number of Islands

A grid of land (1) and water (0). Land cells that touch up, down, left, or right form one island. How many islands are there? Paint the grid below and watch them get counted.

Number of Islands · DFSLeetCode #200
🏝️ count 1scanning…
function numIslands(grid) {
let count = 0
for (let r = 0; r < rows; r++)
for (let c = 0; c < cols; c++)
if (grid[r][c] === '1') { // new land
count++
dfs(grid, r, c) // sink island
}
return count
}
// dfs floods 4-dir neighbors ('1'->'0'), so each island is counted once · O(R·C)
✏️ EDIT THE GRID — click to toggle land/water
rows 4
cols 5

The problem

You’re given a 2D grid of '1's (land) and '0's (water). An island is a group of land cells connected horizontally or vertically (not diagonally). Count how many islands the grid contains.

For the grid above there are 3 islands: the 2×2 block in the corner, the single cell in the middle, and the pair at the bottom-right.

How it works

Scan every cell. The first time you hit an unvisited land cell, you’ve found a new island — so bump the count, then run a depth-first flood fill that sinks the whole island (marks every connected land cell as visited) so it’s never counted again.

function numIslands(grid) {
  let count = 0
  for (let r = 0; r < rows; r++)
    for (let c = 0; c < cols; c++)
      if (grid[r][c] === '1') {   // new land
        count++
        dfs(grid, r, c)            // sink island
      }
  return count
}

dfs floods the 4-directional neighbours, flipping '1''0', so each island is counted exactly once. Step through the runner above to watch the cursor flood one island at a time and the count tick up.

Complexity. Every cell is visited a constant number of times → time O(rows × cols). The recursion stack can go as deep as the largest island → space O(rows × cols) worst case.

Watch the 60-second version

▶ Watch the 60-second visual on YouTube