↻one more pass.
Graphs · Medium

Number of Islands: the idea to remember.

Count four-directionally connected groups of land cells in a binary character grid.

Solve on LeetCode ↗

The core insight

Whenever land is found, count a new island and flood its entire component, marking visited land as water.

Why it works

Each flood marks exactly one connected component. Later scans cannot count any cell from that component again.

The mistake to avoid

Diagonal neighbors do not connect islands. Mark land when it enters the queue. This implementation mutates the input grid.

Time: O(rows × columns)Space: O(rows × columns) worst case queue

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int numIslands(char[][] grid) {
    if (grid.length == 0) return 0;
    int count = 0;
    for (int r = 0; r < grid.length; r++) for (int c = 0; c < grid[0].length; c++) {
        if (grid[r][c] == '1') { count++; sink(grid, r, c); }
    }
    return count;
}
void sink(char[][] g, int r, int c) {
    Deque<int[]> queue = new ArrayDeque<>(); queue.add(new int[]{r,c}); g[r][c] = '0';
    int[][] directions = {{1,0},{-1,0},{0,1},{0,-1}};
    while (!queue.isEmpty()) {
        int[] cell = queue.remove();
        for (int[] d : directions) {
            int nr = cell[0] + d[0], nc = cell[1] + d[1];
            if (nr >= 0 && nr < g.length && nc >= 0 && nc < g[0].length && g[nr][nc] == '1') {
                g[nr][nc] = '0'; queue.add(new int[]{nr,nc});
            }
        }
    }
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.