Fundamentals 6 min read

How to Count Islands in a Grid Using DFS and BFS – Step‑by‑Step Guide

This article explains the classic "Number of Islands" problem, presents two example grids, and demonstrates how depth‑first search (DFS) and breadth‑first search (BFS) can be applied to count isolated land masses in a 2D matrix.

NiuNiu MaTe
NiuNiu MaTe
NiuNiu MaTe
How to Count Islands in a Grid Using DFS and BFS – Step‑by‑Step Guide

Story Origin

While watching the drama "Thirty Something", a line about living like an island inspired the author to discuss the classic "Number of Islands" algorithm problem.

Problem Statement

Given a 2D grid composed of '1' (land) and '0' (water), calculate how many distinct islands exist. An island consists of horizontally or vertically adjacent land cells and is surrounded by water.

Example 1

Input:

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

Output: 3

Example 2

Input:

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

Output: 1

Condition Analysis

Counting islands is essentially counting connected groups of '1's. Two common strategies are:

DFS – depth‑first search, recursively exploring each cell's up, down, left, and right neighbours.

BFS – breadth‑first search, expanding outward level by level like ripples.

During traversal, visited cells must be marked so they are not processed again.

DFS – Depth‑First Search

DFS starts from an unvisited land cell and recursively visits all reachable neighbours in the order up → down → left → right, marking each as visited. The article walks through a detailed example, showing how the search moves from cell to cell until the entire island is explored.

BFS – Breadth‑First Search

BFS processes cells in a queue, exploring all four neighbours of the current cell before moving to the next layer, similar to water ripples expanding outward. Starting from a land cell, it enqueues reachable neighbours, marks them visited, and continues until the whole island is covered.

Island Recap

Both DFS and BFS produce the same island count; DFS code is usually shorter, while BFS requires an explicit queue. For better performance, marking visited cells or applying memoization is recommended.

In the presented grid, the algorithm determines that there is only one island.

DFSBFSgraph traversalgrid algorithmisland counting
NiuNiu MaTe
Written by

NiuNiu MaTe

Joined Tencent (nicknamed "Goose Factory") through campus recruitment at a second‑tier university. Career path: Tencent → foreign firm → ByteDance → Tencent. Started as an interviewer at the foreign firm and hopes to help others.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.