Max Area of Island

Find the biggest island in a grid of land and water by flooding each island from its first cell and counting its cells.

Given a grid of 0s and 1s with m rows and n columns, where 0 is water and 1 is land, find the largest island. An island is a group of 1s joined to each other up, down, left or right. Cells that touch only at a corner are not joined. The area of an island is the number of cells in it. Return the largest area, or 0 if the grid has no land.

Example 1
Input: grid =
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Output: 6
Explanation: the largest island starts at row 3, column 8 and has 6 cells. Its cell at row 5, column 10 touches the island below it only at a corner, so the two stay separate.
Example 2
Input: grid = [[0,0,0,0,0,0,0,0]]
Output: 0
Solution

The Idea

Imagine a map seen from above and cut into squares, where each square is either sea or land. Squares of land that share an edge belong to the same island. The question is how many squares the biggest island covers. By eye, you would spot the patches of land, count the squares in each, and remember the biggest count.

Look at the picture below. It draws Example 1, with row numbers on the left and column numbers on top. Each blue or orange square is a 1, and each "area" label gives the size of the island next to it.

The grid of Example 1, rows 0 to 7 and columns 0 to 12. Its land cells form six islands with areas 1, 4, 4, 5, 6 and 5. The largest, area 6, is orange. Its cell at row 5, column 10 meets the island below only at a corner, marked corner only: not joined.

There are six islands, with areas 1, 4, 4, 5, 6 and 5. The orange one, labelled "area 6", covers row 3, columns 8 and 10, row 4, columns 8, 9 and 10, and row 5, column 10. Now look at the circle marked "corner only: not joined". The orange cell at row 5, column 10 and the blue cell at row 6, column 9 meet only at a corner. So the island labelled "area 5" at the bottom is separate, and the answer is 6, not 11.

The eye sees the patches at once, but a program reads one cell at a time. That raises two questions. When the program reaches a land cell, how does it find every other cell of the same island? And how does it avoid counting a cell, or a whole island, twice?

For the first question, spread out from that cell. From row 3, column 8, step to each land neighbour above, below, left and right, then on to their land neighbours, until no new land is in reach. It works like water poured on one square that runs into every square of land joined to it, which is why this is called a flood fill. Counting the squares it reaches gives the island's area.

This grid is a graph in disguise. Each land cell is a point, and two land cells that share an edge are linked. An island is a group of points that can all reach each other through such links, which is called a connected component. The answer is the size of the largest one.

Solution Approach

The code needs three decisions about the flood fill: where each flood fill starts, how it counts one island, and how counted cells are marked; a last, optional part handles very large islands.

Where each flood fill starts

Which cells should start a flood fill? Scan the grid row by row, left to right, and start one at each 1 the scan meets. In Example 1 the scan meets row 0, column 2 first, then row 0, column 7. Every island has a first cell in this order, so none is missed.

The scan also meets cells of islands it has already measured, though. Row 1, column 7 belongs to the island that started at row 0, column 7. Keeping a fresh list of visited cells for each start does not help: an island is then measured again from each of its cells. On a grid of all land, that is m × n flood fills of m × n cells each. It is better for each flood fill to leave a mark that the scan can see.

Counting one island

How does a flood fill count? Through a method area(grid, r, c) that returns the number of land cells reachable from row r, column c. If that cell is water or outside the grid, the answer is 0. Otherwise it is 1, for the cell itself, plus area of its four neighbours.

area calls itself on the neighbours, so it is recursive: each call settles one cell and leaves the rest to the calls it makes. area(grid, 3, 8) first calls the cell below, row 4, column 8, and that call goes down again before any other direction is tried. Following one path as deep as it goes before turning back is called depth-first search (DFS).

Marking counted cells

What stops the flood fill from walking back? Row 3, column 8 is the neighbour above row 4, column 8. Without a mark, the call for row 4 would count row 3 again, which would count row 4 again, back and forth without end.

The fix is to set a cell to 0 as soon as it is counted, before area calls its neighbours. The cell is sunk: it turns into water, so any later call that reaches it gets 0. Sinking also settles the scan. Once an island is measured, all its cells are 0, so the scan passes over them and starts no second flood fill there.

Sinking changes the caller's grid. If the grid is still needed afterwards, pass a copy, or keep a separate boolean array of visited cells, at the cost of m × n extra values.

Optional: a stack of cells instead of recursion

Is the recursion ever a problem? Each call waits for its neighbours' calls to finish, so a long, winding island makes a long chain of waiting calls. Java keeps that chain on the thread's call stack, which has a limited size. On a 1000 × 1000 grid of all land, the solution below stopped with StackOverflowError.

For grids that big, keep the cells still to visit in an ArrayDeque used as a stack, and loop until it is empty. Each loop takes one cell off, counts it, and pushes its land neighbours after sinking them, so the counting and sinking stay the same.

Java Solution

The method maxAreaOfIsland works in these steps:

  1. First, set best to 0. It holds the largest area found so far, and it stays 0 if the grid has no land.
  2. Scan 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.
  3. When grid[r][c] is 1, it is the first cell of an island not measured yet. Call area(grid, r, c) and keep the larger of its result and best in best.
  4. Inside area, return 0 if row r, column c is outside the grid or not 1. Otherwise set grid[r][c] to 0, and return 1 plus the calls on the cells below, above, right and left.
  5. After the scan has passed every cell, best is the area of the largest island, and the method returns it.

The main method prints four grids row by row, each with its largest area: both examples, two land cells that touch only at a corner, and a 2 × 3 grid of all land. After Example 1 it also counts the land cells left in that grid.

Java
public class MaxAreaOfIsland {

    public static int maxAreaOfIsland(int[][] grid) {
        int best = 0;
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[0].length; c++) {
                if (grid[r][c] == 1) {                    // the first cell of a new island
                    best = Math.max(best, area(grid, r, c));
                }
            }
        }
        return best;
    }

    private static int area(int[][] grid, int r, int c) {
        if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != 1) {
            return 0;                                     // outside, water or counted already
        }
        grid[r][c] = 0;                                   // sink the cell so it is counted once
        return 1 + area(grid, r + 1, c) + area(grid, r - 1, c)
                 + area(grid, r, c + 1) + area(grid, r, c - 1);
    }

    static void print(int[][] grid) {
        for (int[] row : grid) {
            StringBuilder sb = new StringBuilder("  ");
            for (int v : row) {
                sb.append(v).append(' ');
            }
            System.out.println(sb.toString().stripTrailing());
        }
    }

    static void run(String name, int[][] grid) {
        System.out.println(name + ":");
        print(grid);
        System.out.println("largest area = " + maxAreaOfIsland(grid));
        System.out.println();
    }

    public static void main(String[] args) {
        int[][] example1 = {
            {0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
            {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0},
            {0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}
        };
        run("Example 1", example1);
        int left = 0;
        for (int[] row : example1) {
            for (int v : row) {
                left += v;
            }
        }
        System.out.println("land cells left in Example 1 afterwards = " + left);
        System.out.println();
        run("Example 2", new int[][] {{0, 0, 0, 0, 0, 0, 0, 0}});
        run("Diagonal cells only", new int[][] {{1, 0}, {0, 1}});
        run("All land", new int[][] {{1, 1, 1}, {1, 1, 1}});
    }
}

Running it prints:

Output
Example 1:
  0 0 1 0 0 0 0 1 0 0 0 0 0
  0 0 0 0 0 0 0 1 1 1 0 0 0
  0 1 1 0 1 0 0 0 0 0 0 0 0
  0 1 0 0 1 1 0 0 1 0 1 0 0
  0 1 0 0 1 1 0 0 1 1 1 0 0
  0 0 0 0 0 0 0 0 0 0 1 0 0
  0 0 0 0 0 0 0 1 1 1 0 0 0
  0 0 0 0 0 0 0 1 1 0 0 0 0
largest area = 6

land cells left in Example 1 afterwards = 0

Example 2:
  0 0 0 0 0 0 0 0
largest area = 0

Diagonal cells only:
  1 0
  0 1
largest area = 1

All land:
  1 1 1
  1 1 1
largest area = 6

Example 1 prints largest area = 6, the orange island from the picture. The next line, land cells left in Example 1 afterwards = 0, shows the cost of sinking: all 25 land cells of the six islands were turned into water, so the caller's grid is used up.

Under "Diagonal cells only", the 1 at row 0, column 0 and the 1 at row 1, column 1 meet only at a corner. Each is an island on its own, so the line reads largest area = 1, not 2. Example 2 has no land, so best never moves from 0. In "All land", the first flood fill sinks all six cells, and the scan finds nothing else.

Complexity

The scan looks at every cell once, and the flood fills together count each land cell once.

  • Time: O(m × n), because the scan visits each of the m × n cells once, and area counts and sinks each land cell once, then checks it at most four more times from its neighbours.
  • Space: O(m × n) in the worst case, because sinking needs no extra array, but an island that winds through the whole grid keeps up to m × n calls waiting on the call stack.

Counting the islands instead of measuring them is Number of Islands.