Tech Interview RoomStudy guides

Graphs

Count the number of islands in a grid.

Intermediate · 2 min read · Lesson 1 of 4 in Graphs

Problem

Given a grid of '1' (land) and '0' (water), count connected groups of land (4-directional adjacency).

Approach

Scan every cell; when you find unvisited land, increment the count and flood-fill the whole island (BFS or DFS) marking cells visited. BFS with an explicit queue avoids stack overflow on big grids. Union-Find is an alternative that also supports adding land dynamically.

java
import java.util.ArrayDeque;
import java.util.Deque;

class NumberOfIslands {
    private static final int[][] DIRS = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    static int count(char[][] grid) {
        int rows = grid.length, cols = grid[0].length, islands = 0;
        boolean[][] seen = new boolean[rows][cols];
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                if (grid[r][c] != '1' || seen[r][c]) continue;
                islands++;
                Deque<int[]> queue = new ArrayDeque<>();
                queue.offer(new int[] {r, c});
                seen[r][c] = true;
                while (!queue.isEmpty()) {
                    int[] cell = queue.poll();
                    for (int[] d : DIRS) {
                        int nr = cell[0] + d[0], nc = cell[1] + d[1];
                        if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == '1' && !seen[nr][nc]) {
                            seen[nr][nc] = true;
                            queue.offer(new int[] {nr, nc});
                        }
                    }
                }
            }
        }
        return islands;
    }

    public static void main(String[] args) {
        char[][] grid = {
            "11000".toCharArray(),
            "11000".toCharArray(),
            "00100".toCharArray(),
            "00011".toCharArray()
        };
        System.out.println(count(grid));   // 3
    }
}

Complexity

O(rows × cols) time and space.

Follow-up questions interviewers ask

Try answering each one before you open it.

Implement it with Union-Find. When is that better?

Give each land cell an id, union it with land neighbours, and count distinct roots (start with the number of land cells and decrement on each successful union). With path compression and union by rank, operations are nearly O(1). It shines for the "number of islands II" variant, where land is added one cell at a time and you must report the count after each addition without re-scanning the grid.

How would you find the largest island's area?

During each flood fill count the cells visited and keep the maximum. Same O(rows × cols) complexity.