Number of Islands

Free with account Updated Nov 19, 2026 · 5 min read
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

    The grid has a 2×2 block of land, a single land cell in the middle and a pair at the bottom right: three islands.
    The grid has a 2×2 block of land, a single land cell in the middle and a pair at the bottom right: three islands.
    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

    1. Do diagonal cells connect? (Here: no; only four directions.)
    2. Can I modify the grid? If yes, sink land in place; otherwise use a separate visited set.
    3. How big can the grid be? Large grids make recursive DFS risky.
    4. Is the grid rectangular? (Here: yes.)