Topics/Graphs — BFS & DFS/Number of islands

Pattern

Number of islands

Number of islands is a reusable approach under Graphs — BFS & DFS. Once you recognize the shape of the input and the ask, this pattern gives you a standard plan instead of inventing a new algorithm from scratch.

Graphs — BFS & DFSTrees & GraphsPattern

When to use it

Reach for Number of islands when a graphs — bfs & dfs problem matches the cues in this lesson — especially after you’ve ruled out a brute-force nested scan.

How it works

  1. Restate the Graphs — BFS & DFS problem in one sentence and name the constraint that Number of islands exploits.
  2. Sketch the invariant Number of islands maintains (what stays true after each step).
  3. Walk a tiny example by hand, writing the state after every update.
  4. Translate that walk into code in your interview language, then list edge cases.

Solution

Reference implementation in C#, Python, Java, JavaScript, and C++.

Exact solutionNumber of islands

Why interviewers care

Interviewers grade pattern recognition. Naming Number of islands early shows you can classify the problem inside Trees & Graphs.

Drill Number of islands with Graphs — BFS & DFS problems — filter the bank and solve 2–3 Easy/Medium items while saying the invariant out loud.

Watch-outs

  • !Missing visited → infinite loops
  • !Directed vs undirected edges
  • !1-index vs 0-index nodes
Loading visualization…

Practice this

Related Graphs — BFS & DFS problems — open any one and apply Number of islands.

Search bank →

More under Graphs — BFS & DFS

← Back to Graphs — BFS & DFS lesson