Skip to content
AI360Xpert
Beta
Difficulty: MediumGraphs

Number of Islands

Problem in Plain English

Given a grid of land and water cells, count how many islands appear. Each island is a group of land cells joined horizontally or vertically.

Problem Statement

Given a rectangular grid of characters "1" (land) and "0" (water), return the number of islands.

Two land cells belong to the same island if a path of land cells joins them using only up, down, left and right moves. Diagonal contact does not connect islands. Treat the grid boundary as surrounded by water.

Constraints

  • m == grid.length and n == grid[i].length; all rows have the same length.
  • 1≤m,n≤3001 \le m, n \le 300.
  • Every cell is the character "0" or "1".

Examples

Example 1

Input
grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
Output
1

Every land cell touches another through shared sides, so the grid holds a single island.

Example 2

Input
grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
Output
3

The top-left four cells form one island. The cell (2, 2) is a second, and (3, 3) with (3, 4) is a third. Although (2, 2) and (3, 3) meet diagonally, no shared side joins them, so the answer is 3.

Example 3

Input
grid = [["0"]]
Output
0

The smallest allowed grid contains only water. There is no starting land cell, so no traversal begins and the answer is 0.

Example 4

Input
grid = [["1"]]
Output
1

A single land cell needs no land neighbours to form an island. The scan counts it once and its traversal immediately finishes.

Intuition

Think of each land cell as a graph vertex and each shared side between land cells as an edge. An island is one connected component: all cells reachable from one starting land cell. In Example 1, the nine land cells are reachable from (0, 0), even though some are far away in the row scan. Count a component only when the scan finds unclaimed land, then claim every reachable cell before continuing. A separate visited grid preserves the input; changing land to water uses the input itself as the visited record.

Approaches

BFS With Visited

Solution Details

Reveal BFS With Visited: intuition, complexity, and code

Hints

Hint 1
Model land cells joined by shared sides as one graph component. Does the count depend on how many cells that component contains?
Hint 2
During the row scan, start a traversal only at land that no previous traversal has claimed.
Hint 3
Use a queue or explicit stack to claim the entire component. Mark a cell before scheduling it; choose a visited matrix to preserve the grid or sink cells if mutation is acceptable.

Edge Cases

  • An all-water grid, including [["0"]], returns 0 without a traversal.
  • An all-land grid, including the 300 by 300 maximum, returns 1. An explicit traversal avoids recursive stack overflow.
  • A checkerboard of alternating land and water has one island per land cell; diagonal neighbours remain separate. A 300 by 300 checkerboard has 45000 islands.
  • A single row or column can contain multiple separated runs of land; each run is one island.
  • Islands may touch any border. Out-of-bounds positions are skipped, not accessed or counted.
  • The visited approach can be called again on the same unchanged grid. After sink DFS, every cell is water, so a second call on that same object returns 0. Preserve an original copy if both approaches must run on the same input.

Common Mistakes and Interview Tips

  • Counting each land cell instead of each fresh traversal start; the nine land cells in Example 1 form only one island.
  • Using eight directions merges diagonally touching islands that must remain separate.
  • Marking after removing a queue or stack entry allows converging paths to insert duplicates. Mark when scheduling.
  • Using recursive DFS without considering the maximum grid size; long connected regions exceed common Python, Java and JavaScript call-stack limits.
  • Calling JavaScript Array.shift repeatedly can add linear work per removal. Use a head index to keep total queue work linear.
  • Creating visited rows by repeating one mutable row makes unrelated positions share flags. Allocate independent rows.
  • Calling sinking constant-space ignores the explicit stack. Explain input mutation and traversal storage separately in an interview; cloning only the outer grid array does not protect shared inner rows.

Key Takeaway

To count connected components, scan for unclaimed vertices, start one traversal per fresh vertex, and mark every reachable vertex before continuing. Grid side-adjacency supplies the graph edges. A visited structure preserves the map; mutation can replace those marks but does not remove traversal memory.