Number of Islands


Problem Link: Number of Islands


Problem Statement

Given an m × n 2D binary grid grid, where:

Return the number of islands. An island is defined as a group of adjacent lands connected horizontally or vertically, and all edges of the grid are surrounded by water.


Examples

Example 1

Input:
[
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1

Example 2

Input:
[
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3

Constraints


Intuition

We treat the grid as a graph:

When you encounter a '1' that hasn't been visited, start a graph traversal to mark all reachable land cells, and increment the island count.

This can be done through:


Algorithm

  1. Initialize counter count = 0.

  2. Loop through every cell (i, j):

    • If grid[i][j] == '1':

      • Call dfs(i, j) to mark all connected land.

      • Increment count.

  3. Return count.

DFS marks visited land by changing '1''0' (in-place) or using a separate visited array.

Java Code (In-place Modification)

class Solution {
    public int numIslands(char[][] grid) {
        int m = grid.length, n = grid[0].length, count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1') {
                    count++;
                    dfs(grid, i, j);
                }
            }
        }
        return count;
    }
    private void dfs(char[][] grid, int i, int j) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] != '1') {
            return;
        }
        grid[i][j] = '0';
        dfs(grid, i + 1, j);
        dfs(grid, i - 1, j);
        dfs(grid, i, j + 1);
        dfs(grid, i, j - 1);
    }
}

Dry Run

grid = [
  ['1','1','0','0','0'],
  ['1','1','0','0','0'],
  ['0','0','1','0','0'],
  ['0','0','0','1','1']
]

Complexity (DFS)

Metric Value
Time Complexity O(m × n)
Space Complexity O(m × n) stack (worst-case recursion)

All cells are visited once, and each DFS explores connected neighbors.


Algorithm

Similar to DFS, but uses a queue to explore connected land layer by layer.

Java Code

class Solution {
    public int numIslands(char[][] grid) {
        int m = grid.length, n = grid[0].length, count = 0;
        int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1') {
                    count++;
                    grid[i][j] = '0';
                    Queue<int[]> q = new LinkedList<>();
                    q.add(new int[]{i,j});
                    while (!q.isEmpty()) {
                        int[] cur = q.poll();
                        for (int[] d : dirs) {
                            int ni = cur[0] + d[0], nj = cur[1] + d[1];
                            if (ni>=0 && ni<m && nj>=0 && nj<n && grid[ni][nj]=='1') {
                                grid[ni][nj] = '0';
                                q.add(new int[]{ni,nj});
                            }
                        }
                    }
                }
            }
        }
        return count;
    }
}

Complexity (BFS)

Metric Value
Time Complexity O(m × n)
Space Complexity O(m × n) in queue (max)

Optional: Union-Find (Disjoint Set)

This method builds a union-find structure over cells, merging adjacent lands. After processing, the number of unique roots = island count. Best when dynamic updates are needed.


Applications


Summary