Hourly DSABlog

Number of Islands: Count Starts, Not Land Cells

By Hourly DSA · · 4 min read

Count islands by starting a traversal whenever you find land that no earlier traversal has visited. Each traversal covers one complete connected region. Increase the count once for that region, regardless of how many cells it contains.

The key is defining connected. We'll use four-directional adjacency: up, down, left, and right. Diagonal contact does not join two islands.

Read the grid as a graph

Let 1 mean land and 0 mean water:

1 1 0 0
0 1 0 1
1 0 0 1

Each land cell is a vertex. Two vertices share an edge if their cells touch along a side. There is no need to build a separate adjacency list; a cell's coordinates let you generate its four possible neighbors.

The top-left region contains three cells. The rightmost column contains a separate two-cell region. The bottom-left cell is a third island. Although it touches the middle row's land diagonally, that contact does not count.

Count a new traversal once

Scan the grid row by row. When a cell is water or already seen, skip it. Otherwise, increment the island count and explore all land reachable from that cell.

islands = 0
seen = empty set
for each cell in the grid:
    if cell is land and cell is not in seen:
        islands += 1
        mark cell seen
        stack = [cell]
        while stack is not empty:
            current = pop(stack)
            for each in-bounds side neighbor of current:
                if neighbor is land and neighbor is not in seen:
                    mark neighbor seen
                    push neighbor onto stack
return islands

Mark a cell when you push it. Two cells can share the same neighbor; marking on discovery prevents both from adding a pending copy.

Follow what the outer scan skips

The first cell starts traversal number one. That traversal marks the two land cells in the top row and the land cell directly below the second one.

When the outer scan later reaches either of those other cells, it skips them. They have already been assigned to a region.

The land at the end of the middle row starts traversal number two, which also reaches the land beneath it. Finally, the bottom-left cell starts traversal number three.

Counting every land cell would return 6. Counting traversal starts returns the required 3.

Why does one start mean one island?

A traversal follows only edges between adjacent land cells, so it cannot leave its starting island. It also keeps exploring every discovered cell's neighbors, so it eventually reaches every cell connected to its start.

Afterward, all cells in that island are marked. The outer scan cannot count it again. Conversely, every island has a first cell encountered by the scan, and that cell starts a traversal if its island has not yet been explored.

Either DFS or BFS works. No shortest path is requested, so the layer order of BFS is unnecessary for correctness.

Choose how to remember visits

A separate seen structure preserves the original grid. If changing the input is allowed, you can instead turn discovered land into water before adding it to the stack.

That avoids a separate visited record, but the traversal stack still uses memory. It also destroys the original land map, which may matter to later code.

For an R-by-C rectangular grid, the scan and traversals take O(RC) time. Each cell has only four possible neighbors. Worst-case auxiliary space is O(RC), including traversal state. Recursive flood fill can also reach that depth on a long narrow island.

An empty grid or an all-water grid returns zero. If diagonal moves are allowed, update the neighbor rule and expect some regions to merge.

Change one adjacency rule

For a two-by-two grid with land only in the top-left and bottom-right cells, how many islands exist?

Two with side adjacency; one if diagonals also connect. The traversal follows the problem's definition of an edge.

Use Hourly DSA to practice identifying that definition before choosing an algorithm.

Explore another way to represent connected groups when connections are added over time.

Union-Find Explained: Track Connected Components →