Practice LeetCode 200 · Number of Islands · GFG · Find the Number of Islands
GraphsDFSFlood FillGrid

Depth-First Search · Number of Islands

Each blob of connected land is one island. DFS dives into a land cell, floods the entire connected region, then surfaces. Count how many times you had to start a fresh dive.

The idea

Scan the grid. When you hit an unvisited 1, that's a new island, so bump the count and DFS-flood every connected land cell, sinking them so you never recount.

DFS goes deep first: it fully explores one branch (recursion / explicit stack) before backtracking.

The rules

  • 1 = land, 0 = water
  • Cells connect 4-directionally (up/down/left/right)
  • A new dive from unvisited land = +1 island
  • Sinking to 0 doubles as the visited marker

Watch each island flood

slowfast
Step 0
Islands
0
Land visited
0
Island size
0
Stack depth
0

C++

void dfs(vector<vector<char>>& grid, int r, int c) {
    int rows = grid.size(), cols = grid[0].size();
    if (r < 0 || c < 0 || r >= rows || c >= cols) return;
    if (grid[r][c] != '1') return;      // water or already sunk

    grid[r][c] = '0';                    // sink = mark visited
    dfs(grid, r - 1, c);
    dfs(grid, r + 1, c);
    dfs(grid, r, c - 1);
    dfs(grid, r, c + 1);
}

int numIslands(vector<vector<char>>& grid) {
    int count = 0;
    for (int r = 0; r < grid.size(); r++)
        for (int c = 0; c < grid[0].size(); c++)
            if (grid[r][c] == '1') {
                count++;                    // new island found
                dfs(grid, r, c);            // flood the whole thing
            }
    return count;
}
Time
O(R × C)

Each cell is examined a constant number of times across the scan and floods.

Space
O(R × C)

Recursion stack in the worst case (grid is entirely land, one giant snake).

Islands
= dives

Count equals the number of times the outer scan kicks off a fresh DFS.

  • DFS vs BFS here: both count islands correctly. DFS is shorter to write (recursion), BFS avoids stack-overflow on huge grids.
  • Sinking land to '0' in place saves a separate visited array. If you can't mutate input, keep a visited[][].
  • Deep recursion on a massive all-land grid can blow the stack, switch to an explicit stack or BFS then.
  • For 8-directional islands, just add the 4 diagonal offsets.
  • Same flood-fill pattern solves surrounded regions, max area of island, and flood fill (LC 733).