Algo-Sim › Grid Graphs

Number of Islands (DFS)

Medium · Grid Graphs · step through it in Java, Python and C++ on your own input

Count the islands with a recursive flood fill: each new land cell starts a DFS that sinks its whole island.

Problem

Given a grid of 1 (land) and 0 (water), count the islands: groups of land cells joined horizontally or vertically. This version sinks each island with a recursive DFS.

Constraints

Edge cases to test

Follow-up questions

What is the risk of recursion here?
An island can have m·n cells, so the call stack can reach m·n frames; BFS or an explicit stack avoid that.
How do you count distinct island shapes?
Record each island’s cells relative to its first cell and store the shapes in a set (LC 694).

Solution

Java

public int numIslands(char[][] grid) {
    int islands = 0;
    for (int r = 0; r < grid.length; r++) {
        for (int c = 0; c < grid[0].length; c++) {
            if (grid[r][c] != '1') continue;
            islands++;
            dfs(grid, r, c);
        }
    }
    return islands;
}

private void dfs(char[][] grid, int r, int c) {
    if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || grid[r][c] != '1') return;
    grid[r][c] = '0';
    dfs(grid, r + 1, c);
    dfs(grid, r - 1, c);
    dfs(grid, r, c + 1);
    dfs(grid, r, c - 1);
}

Python

def num_islands(grid):
    islands = 0
    for r in range(len(grid)):
        for c in range(len(grid[0])):
            if grid[r][c] != "1":
                continue
            islands += 1
            dfs(grid, r, c)
    return islands

def dfs(grid, r, c):
    if not (0 <= r < len(grid) and 0 <= c < len(grid[0])) or grid[r][c] != "1":
        return
    grid[r][c] = "0"
    dfs(grid, r + 1, c)
    dfs(grid, r - 1, c)
    dfs(grid, r, c + 1)
    dfs(grid, r, c - 1)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int numIslands(vector<vector<char>> &grid) {
        int islands = 0;
        for (int r = 0; r < int(grid.size()); r++) {
            for (int c = 0; c < int(grid[0].size()); c++) {
                if (grid[r][c] != '1')
                    continue;
                islands++;
                dfs(grid, r, c);
            }
        }
        return islands;
    }

    void dfs(vector<vector<char>> &grid, int r, int c) {
        if (r < 0 || c < 0 || r >= int(grid.size()) || c >= int(grid[0].size()) || grid[r][c] != '1')
            return;
        grid[r][c] = '0';
        dfs(grid, r + 1, c);
        dfs(grid, r - 1, c);
        dfs(grid, r, c + 1);
        dfs(grid, r, c - 1);
    }
};

More Grid Graphs problems