Problem Statement

Number of Islands

You are given a grid (a rectangle of squares laid out in rows and columns). Each square holds either a '1', which means land, or a '0', which means water. An island is a group of land squares that touch each other, going up, down, left, or right (not diagonally). Your job is to count how many separate islands there are. Two land squares belong to the same island if you can walk from one to the other by stepping only onto neighboring land.

mediumGraphBFSDFSMatrixGraphsTime: O(m * n) · Space: O(m * n)

Signals to notice

count connected regionsgrid of 1s and 0sflood fill

Brute force first

No simpler alternative — graph traversal is the natural approach. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

DFS/BFS from each unvisited '1', mark all connected land. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Trace it on grid=[["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]

start: count=0, scan row-major from (0,0)
(0,0)='1' -> count=1, dfs sinks connected land {(0,0),(0,1),(1,0),(1,1)} to '0'
scan continues: rest of rows 0-1 now '0', (2,0) (2,1) are '0' -> skip
(2,2)='1' -> count=2, dfs sinks {(2,2)} (no land neighbors) to '0'
(3,3)='1' -> count=3, dfs sinks {(3,3),(3,4)} to '0'
scan finishes, no more '1' cells remain
return count=3

What must stay true

Each DFS/BFS call discovers one complete island and marks it as visited. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Shape of the loop

count = 0
for each cell (i, j) in grid:
    if grid[i][j] == '1':
        count += 1
        dfs(i, j)            # sink island: set '1'->'0', recurse 4 neighbors
return count

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Not marking cells as visited — causes infinite loops or double counting. The fix is usually to return to the meaning of each move, not just the steps themselves.

Graphs Pattern