mediumGraphBFSDFSMatrixGraphs

Number of Islands

mediumTime: 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.

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.

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