Number of Islands
On this page
Problem statement
Given a grid of "1" (land) and "0" (water), count the islands. An island is a group of land cells connected horizontally or vertically; diagonal neighbours don't connect. Everything outside the grid is water.
The most common grid-graph question. Once you see that each island is a connected component, the answer is "scan the grid and start a flood fill at every land cell you haven't visited". Original problem: LeetCode 200.
Example

Input:
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1
Output: 3
Input: [["0"]]
Output: 0
Constraints (assumed)
- 1 ≤ rows, cols ≤ 300.
- Cells are "0" or "1".
What this question tests
- Modelling a grid as a graph without building an adjacency list.
- Counting connected components with BFS or DFS.
- Correct visited handling and bounds checks.
Questions to ask first
- Do diagonal cells connect? (Here: no; only four directions.)
- Can I modify the grid? If yes, sink land in place; otherwise use a separate visited set.
- How big can the grid be? Large grids make recursive DFS risky.
- Is the grid rectangular? (Here: yes.)
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.