Number of Islands

Count the separate patches of land in a grid of land and water cells.

Given a grid of m rows and n columns, where each cell holds the character '1' (land) or '0' (water), return the number of islands. An island is a group of land cells joined to each other up, down, left or right. Cells that touch only at a corner are not joined, and everything outside the grid counts as water.

Example 1
Input: grid = [["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: grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
Output: 3
Solution

The Idea

Picture a map seen from above and cut into squares. Each square is either land, marked '1', or water, marked '0'. An island is a patch of land you can walk across while stepping only up, down, left or right, never diagonally. The question is how many separate patches the map has.

Look at the picture below. It shows the grid of Example 2, with row numbers down the left and column numbers along the top, and a cell is written as (row, column). The four land cells at the top left, (0, 0), (0, 1), (1, 0) and (1, 1), make island 1. The cell (2, 2) stands alone as island 2, and (3, 3) and (3, 4) make island 3.

The grid of Example 2 with row numbers 0 to 3 and column numbers 0 to 4. Island 1 is the four cells at the top left, island 2 is the single cell at (2, 2), and island 3 is (3, 3) and (3, 4). An orange circle marks where (2, 2) and (3, 3) touch only at a corner.

Now look at the orange circle labelled "corner touch". The cells (2, 2) and (3, 3) meet there, but only at a corner, so you cannot step from one to the other. They stay two islands, and the answer is 3, not 2.

Example 2 has seven land cells but only three islands. Counting land cells is easy, so the real question is this: how do we count each island once, however many cells it has?

Read the grid row by row, like a page of text. The first land cell the reading meets, (0, 0), cannot belong to an island counted earlier, so the count becomes 1. Before reading on, walk from (0, 0) to every land cell you can reach and turn each one into water. We will call this sinking the island. When the reading arrives at (0, 1), (1, 0) and (1, 1), they are water already and are not counted again.

The next land the reading meets is (2, 2), so the count becomes 2, and after that (3, 3) makes it 3. The legend on the right of the picture follows the same three stops, from "island 1" down to "island 3".

Seen another way, the grid is a graph: a set of points with links between them. Each land cell is a point, linked to the land cells directly above, below, left and right of it. In Example 2, (0, 0) is linked to (0, 1) and (1, 0), while (2, 2) has no links at all. An island is a group of points that can all reach each other through links, which is called a connected component.

Graph problems often start by building an adjacency list, a list of linked points for every point. This grid needs none: the possible neighbours of a cell (r, c) are always (r - 1, c), (r + 1, c), (r, c - 1) and (r, c + 1), and the code checks them on the spot.

Solution Approach

Turning that idea into code means deciding how the reading finds a new island, how to walk over all its cells, how to remember visited cells and, optionally, how to walk without a long chain of calls.

Finding a new island

When does the reading know it has found a new island? Two loops, one inside the other, visit every cell row by row. Any '1' they meet is a cell that no earlier sinking reached, so it starts an island that has not been counted yet.

Without sinking, every new land cell would have to be checked against all the islands found so far, which means keeping each island's cells and searching through them. Sinking turns that search into a single look at the cell itself.

Walking over the whole island

How do we reach every cell of the island from the one the reading found? A method sink turns its cell into water and then calls itself on the four neighbours. Each of those calls does the same for its own neighbours, so the walk goes as far as it can in one direction before it backs up and tries the next.

A walk that always goes deeper first like this is called depth-first search, or DFS. In Example 2, sinking from (0, 0) first goes down to (1, 0), from there right to (1, 1), and from there up to (0, 1).

Every call starts with one check: if its cell lies outside the grid or does not hold '1', it returns at once. That single check covers the edges of the grid, water, and cells already sunk. The grid holds characters, so the check compares with '1' in quotes. The number 1 would never match, because the character '1' has the code 49.

Remembering visited cells

How does the walk avoid going round in circles between neighbours? Writing '0' into a cell is the memory. A sunk cell fails the check, so no cell is sunk twice and the walk always ends.

The price is that the input grid changes: once the count is done, every land cell has become water. If the caller still needs the grid, copy it first, or keep a separate boolean grid of visited cells and leave the input alone.

Optional: walking with a queue

Each sink call waits for the calls it makes, and Java keeps those waiting calls on the thread's stack, which has a limited size. On a grid that is all land, the chain of waiting calls can grow as long as the number of cells. On a 1000 × 1000 grid of land, counting with sink stops with a StackOverflowError.

To avoid the deep chain, put the cells still to visit in a queue, such as an ArrayDeque, and take them out one at a time in a loop. That visits the island in rings, nearest cells first, which is called breadth-first search, or BFS. The count comes out the same.

Java Solution

The method numIslands works in these steps:

  1. First, set count to 0. Then go over the grid with two loops, one inside the other: the outer loop moves r down the rows, and the inner loop moves c along the columns of row r.
  2. When grid[r][c] is '1', add 1 to count and call sink(grid, r, c) to turn the whole island into water.
  3. sink returns at once if (r, c) is outside the grid or does not hold '1'. Otherwise it sets grid[r][c] to '0' and calls itself on the cells below, above, right and left.
  4. When both loops are done, return count.

The helper grid builds the char[][] from one string per row, and show prints a grid row by row before counting it. The main method runs both examples, two land cells that touch only at a corner, a ring of land around one water cell, and a grid with no land.

Java
public class NumberOfIslands {

    public static 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++;              // land no sinking has reached: a new island
                    sink(grid, r, c);     // turn the whole island into water
                }
            }
        }
        return count;
    }

    private static void sink(char[][] grid, int r, int c) {
        if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') {
            return;                       // outside the grid, water, or already sunk
        }
        grid[r][c] = '0';
        sink(grid, r + 1, c);             // down
        sink(grid, r - 1, c);             // up
        sink(grid, r, c + 1);             // right
        sink(grid, r, c - 1);             // left
    }

    static char[][] grid(String... rows) {
        char[][] g = new char[rows.length][];
        for (int i = 0; i < rows.length; i++) {
            g[i] = rows[i].toCharArray();
        }
        return g;
    }

    static void show(String name, char[][] g) {
        System.out.println(name + ":");
        for (char[] row : g) {
            System.out.println("  " + new String(row));
        }
        System.out.println("  islands: " + numIslands(g));
    }

    public static void main(String[] args) {
        show("Example 1", grid("11110", "11010", "11000", "00000"));
        show("Example 2", grid("11000", "11000", "00100", "00011"));
        show("Corners only", grid("10", "01"));
        show("Ring around water", grid("111", "101", "111"));
        show("All water", grid("000", "000"));
    }
}

Running it prints:

Output
Example 1:
  11110
  11010
  11000
  00000
  islands: 1
Example 2:
  11000
  11000
  00100
  00011
  islands: 3
Corners only:
  10
  01
  islands: 2
Ring around water:
  111
  101
  111
  islands: 1
All water:
  000
  000
  islands: 0

Example 1 prints islands: 1. Its nine land cells all hang together, so the first sink, from (0, 0), reaches every one of them, and the reading finds no more land. Example 2 prints islands: 3, the three islands in the picture.

The grid labelled "Corners only", 10 above 01, prints islands: 2. It is the corner touch from the picture again, and the two cells stay apart. The ring prints islands: 1: the land goes all the way round the water cell in the middle, and the water inside does not split it. The all-water grid prints islands: 0, because the reading never meets a '1'.

Sinking is what makes the count one per island, not one per cell. A version that adds 1 for every '1' without sinking returns 9 for Example 1, one for each land cell.

Complexity

The reading looks at every cell once, and sinking changes each land cell once.

  • Time: O(m × n), because the two loops read each of the m × n cells once, and sink turns each land cell into water once, with at most four more quick checks from its neighbours.
  • Space: O(m × n) in the worst case, because the grid itself records the sunk cells, but on a grid that is all land the chain of waiting sink calls can be as long as the number of cells.

To measure the size of each island instead of counting them, see Max Area of Island.