Number of Islands

Medium#200grid

You get a map of land and water cells. Land cells that touch by a side form one island; touching by a corner does not count. Count the islands. Our map has 4 rows: # . # ., # . # ., # # # ., . . . # (# is land) — the answer is 2: the first seven land cells make one U-shaped island, and the cell in the bottom right corner is alone.

input
grid: an m × n map, each cell '1' for land or '0' for water.
returns
The number of islands: groups of land cells joined up, down, left or right, not diagonally. Beyond the edges of the map is water.
constraints
  • m = grid.length, n = grid[i].length, 1 ≤ m, n ≤ 25
  • grid[i][j] is '0' or '1'
our 16 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {character[][]} grid
 * @return {number}
 */
function numIslands(grid) {

}
Ctrl ↵
format
reset

saved in this browser

16 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more depth-first search (dfs) problems

Pattern “Depth-first search (DFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.