AlgoMaster Logo

Number of Islands

mediumFrequency8 min readUpdated June 23, 2026

Understanding the Problem

We have a 2D grid of characters where '1' represents land and '0' represents water. Two land cells belong to the same island if they are adjacent horizontally or vertically (not diagonally). We need to count how many distinct islands exist in the grid.

This is a connected components problem on a graph. Each '1' cell is a node, and there is an edge between two nodes if they are horizontally or vertically adjacent and both are '1'. The number of islands is the number of connected components in this implicit graph.

Once we find any unvisited land cell, we can explore all cells connected to it and mark them visited. That entire connected group counts as one island. We then move on and look for the next unvisited land cell.

Key Constraints:

  • 1 <= m, n <= 300 means the grid can have up to 300 x 300 = 90,000 cells. An O(m n) solution is well within time limits, and so is the O(m n alpha(m n)) of Union Find.
  • grid[i][j] is '0' or '1', so there are no other characters to handle. DFS, BFS, and Union Find all fit within these bounds.

Approach 1: DFS (Depth-First Search)

Intuition

Scan the grid from top-left to bottom-right. The first '1' we reach that has not been visited yet belongs to a new island. We flood fill outward from that cell using DFS, marking every connected '1' as visited so it is not counted again. Once the DFS finishes, one island has been fully explored. We increment the count and keep scanning.

To avoid a separate visited array, we modify the grid in-place. When we visit a '1', we change it to '0'. Every cell we touch gets "sunk," so later iterations of the scan skip over it.

Algorithm

  1. Initialize an island counter to 0.
  2. Iterate through every cell in the grid (row by row, column by column).
  3. When we find a cell with value '1', increment the island counter.
  4. Run DFS from that cell: mark the current cell as '0', then recursively visit all four neighbors (up, down, left, right) that are '1'.
  5. After scanning all cells, return the island counter.

Example Walkthrough

1Initial grid. Scan from (0,0). islands = 0
0
1
2
3
4
0
scan
1
1
0
0
0
1
1
1
0
0
0
2
0
0
1
0
0
3
0
0
0
1
1
1/8

Code

The DFS approach runs in O(m * n) time, which is optimal. Its weakness is the recursion stack: on a grid that is entirely land, the recursion can go 90,000 levels deep and overflow the call stack. The next approach replaces the recursion with an explicit queue, which moves the traversal state to the heap.

Approach 2: BFS (Breadth-First Search)

Intuition

BFS uses the same principle as DFS: find an unvisited '1', explore all connected '1' cells, count that group as one island. The difference is mechanical. Instead of the system call stack (recursion), it uses an explicit queue, which removes the stack overflow risk on large islands. BFS explores in layers outward from the starting cell, so the queue holds at most the cells along the current frontier rather than the whole island.

Algorithm

  1. Initialize an island counter to 0.
  2. Iterate through every cell in the grid.
  3. When we find a '1', increment the island counter, sink the cell to '0', and add it to a queue.
  4. While the queue is not empty, dequeue a cell, and for each of its four neighbors that is '1', sink it to '0' and enqueue it.
  5. After scanning all cells, return the island counter.

Example Walkthrough

1Initial grid. Scan from (0,0). islands = 0
0
1
2
0
scan
1
1
0
1
1
0
0
2
0
0
1
1/7

Code

Both DFS and BFS modify the input grid in-place to mark visited cells. When the grid must stay unchanged, Union Find tracks connected components in a separate data structure and leaves the grid alone.

Approach 3: Union Find (Disjoint Set Union)

Intuition

Union Find builds islands up incrementally instead of exploring them by traversal. Scan the grid once. For every '1' cell, check its right neighbor and its bottom neighbor. If a neighbor is also '1', union the two cells into the same set.

At the end, the number of distinct sets that contain '1' cells is the number of islands. We track this with a count that starts at the total number of '1' cells and decrements by one every time a union merges two previously separate sets.

This approach leaves the input grid unchanged. It also extends to the dynamic version of the problem (Number of Islands II), where land cells are added one at a time and re-running a full traversal after each addition would be wasteful.

Algorithm

  1. Count the total number of '1' cells. This is our initial island count (each '1' starts as its own island).
  2. Initialize a Union Find structure where each '1' cell is its own parent.
  3. Scan the grid. For each '1' cell, check the cell to its right and the cell below it.
  4. If a neighbor is also '1', union the current cell with the neighbor. If the union merges two previously separate sets, decrement the island count.
  5. Return the final island count.

Example Walkthrough

1Initial grid. 4 land cells -> count = 4. Each is its own set.
0
1
2
0
set 0
1
set 1
1
0
1
set 3
1
0
0
2
0
0
set 8
1
1/7

Code