Number of Islands

Pattern: Connected components and islands

medium

Scan the grid; each time you find land ('1') that has not been visited, count a new island and sink all of it (turn it to '0') with a DFS or BFS over up, down, left and right.

The problem

Given a grid of '1' (land) and '0' (water), return the number of islands: groups of land joined horizontally or vertically.

Think first

  • What counts as a neighbour?
  • How do you make sure an island is counted once?
  • Is it acceptable to change the grid?

Hints

    Brute force, and why it fails

    Union-find over all land cells: also O(R × C).

    The key insight

    Sinking a whole island at the moment it is first seen means every later land cell found starts a new island.

    Dry run

    islands1

    Grid 11000 / 11000 / 00100 / 00011. The first '1' at (0, 0) starts island 1; sinking clears the 2 × 2 block.

    Step 1 of 3

    The plan

    for each cell: if '1': count += 1; sink(cell)
    sink: set to '0' and sink its four neighbours that are '1'
    

    Complexity

    Time
    O(R × C)
    Space
    O(R × C)

    Each cell is sunk at most once; the search stack can hold many cells.

    Edge cases

    • A 1 × 1 grid.
    • A grid with no land (or no walls).
    • Everything connected.
    I've built my logic, show the code

    Java

    class Solution {
        public int numIslands(char[][] grid) {
            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); }   // a new island: sink all of it
            return count;
        }
    
        private void sink(char[][] g, int r, int c) {
            if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] != '1') return;
            g[r][c] = '0';                          // mark it so it is never counted again
            sink(g, r + 1, c); sink(g, r - 1, c); sink(g, r, c + 1); sink(g, r, c - 1);
        }
    }

    C++

    class Solution {
    public:
        int numIslands(vector<vector<char>>& grid) {
            int count = 0;
            for (size_t r = 0; r < grid.size(); r++)
                for (size_t c = 0; c < grid[0].size(); c++)
                    if (grid[r][c] == '1') { count++; sink(grid, static_cast<int>(r), static_cast<int>(c)); }   // sink all of it
            return count;
        }
    
        void sink(vector<vector<char>>& g, int r, int c) {
            if (r < 0 || c < 0 || r >= static_cast<int>(g.size()) || c >= static_cast<int>(g[0].size()) || g[r][c] != '1') return;
            g[r][c] = '0';                          // mark it so it is never counted again
            sink(g, r + 1, c); sink(g, r - 1, c); sink(g, r, c + 1); sink(g, r, c - 1);
        }
    };

    Python

    class Solution:
        def numIslands(self, grid: list[list[str]]) -> int:
            R, C, count = len(grid), len(grid[0]), 0
            for r in range(R):
                for c in range(C):
                    if grid[r][c] == "1":           # a new island: sink all of it
                        count += 1
                        grid[r][c] = "0"
                        st = [(r, c)]
                        while st:
                            a, b = st.pop()
                            for x, y in ((a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)):
                                if 0 <= x < R and 0 <= y < C and grid[x][y] == "1":
                                    grid[x][y] = "0"    # mark it so it is never counted again
                                    st.append((x, y))
            return count

    Common mistakes

    • Counting diagonal neighbours.
    • Deep recursion on a big grid; an explicit stack avoids it.

    Similar problems