Sweaty Imposter

Number of Islands

MediumGraph BFS/DFSBlind 75MidOpen on LeetCodeUpdated

You're given an m x n grid where each cell is "1" (land) or "0" (water). An island is a group of land cells joined horizontally or vertically; cells that touch only diagonally are not connected. Everything outside the grid is water. Return the number of islands. You may modify the grid.

Examples

grid = [["1","1","0"],["1","0","0"],["0","0","1"]] returns 2

110100001
Land is colored. The top-left group and the lone bottom-right cell are the two islands.

The three land cells in the top left touch one another and form one island. The 1 in the bottom right touches no other land, so it is a second island.

grid = [["1","1","1"],["0","1","0"],["1","1","1"]] returns 1

The 1 in the center links the top row to the bottom row, so all seven land cells form a single island.

grid = [["1","0"],["0","1"]] returns 2

1001
Touching at a corner doesn't connect two land cells.

The two land cells meet only at a corner. Diagonal contact doesn't join them, so each is its own island.

Constraints

  • 1 <= m, n <= 300

Hints

Hint 1

Each land cell belongs to exactly one island, how would you mark everything in that island as you find it?

Hint 2
A pointer toward the approach
Hint 3
The full approach, step by step

Drill This: Your Approach First

Approach

Scan every cell. When you hit a "1", you've found a new island: count it, then run a depth-first search from it that turns every connected land cell into "0", so none of them is counted again. Each cell is sunk at most once, so the total work is O(m * n). Space is O(m * n) in the worst case for the recursion stack, when the grid is one big island.

Time

O(m * n)

Space

O(m * n)

Pitfall

The cells are the characters "1" and "0", not integers, so comparing against 1 counts nothing. Sink each cell before recursing into its neighbors, or two neighbors keep calling each other forever.

Solutions

class Solution {
    public int numIslands(char[][] grid) {
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; 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 || j < 0 || i >= grid.length || 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);
    }
}
Drill This