Making a Large Island

Fill one water cell in a grid to make the largest island, by measuring each island once and adding up the islands around each 0.

Given an n × n grid of 0s and 1s, where 1 is land and 0 is water, you may change at most one 0 into a 1. An island is a group of 1s joined up, down, left or right, and its size is its number of cells. Return the size of the largest island the grid can have after the change.

Example 1
Input: grid = [[1,0],[0,1]]
Output: 3
Explanation: changing either 0 joins the two single cells into an island of 3.
Example 2
Input: grid = [[1,1],[1,0]]
Output: 4
Example 3
Input: grid = [[1,1],[1,1]]
Output: 4
Explanation: there is no 0 to change.
Solution

The Idea

Think of the grid as a map seen from above. Each 1 is a square of land and each 0 a square of water. Land squares that share a side belong to the same island, while squares that only meet at a corner do not. You may fill one square of water with land, and you want the biggest island you can end up with.

In Example 1, [[1,0],[0,1]], the two land cells meet only at a corner, so they are two islands of size 1. The 0 at the top right shares a side with both of them. Fill it, and the three cells become one island of 3. Example 3 has no water at all, so nothing can be filled, and the answer is the island already there, 4.

Which 0 should we fill? We could try each one, walk over the island it ends up in and count the cells. But the same big island would then be walked over again for every 0 next to it. Can we know the new size without walking at all?

Look at the picture below. The grid on the left has three islands. On the right, the cells of each island carry a label of their own, 2, 3 or 4, and the size of each island is written underneath. The orange 0 has four neighbours: a 2 above it, a 2 on its left, a 4 below it and a 0 on its right.

A 4 by 4 grid of 0s and 1s, and the same grid with each island labelled: island 2 of size 3, island 3 of size 2, island 4 of size 3. Filling the orange 0 joins islands 2 and 4, so the new island has 1 + 3 + 3 = 7 cells.

Filling the orange 0 joins island 2 and island 4 through it. The new island has 1 + 3 + 3 = 7 cells: the filled cell plus both islands. No walk was needed, only the sizes written down earlier. Island 2 touches the orange 0 twice, from above and from the left, but it is still one island, so its 3 is added once.

So each island needs to be measured only once, as long as its cells say which island they belong to. After that, filling a 0 gives an island of 1 plus the sizes of the different islands among its four neighbours.

Solution Approach

Turning that idea into code means settling three things: how to label and measure each island, how to score each 0, and what to return when there is no 0. Before them comes a look at why the slow way is slow, and after them a shorter, recursive way to walk an island.

Trying every 0

How slow is filling each 0 and counting from scratch? A grid of n rows has n² cells, so there can be about n² zeros, and one count can walk about n² cells. That is about n⁴ steps. With n = 500, the grid has 250,000 cells, and the steps run into billions.

Labelling and measuring each island

Which labels should the islands get? The grid already uses 0 for water and 1 for land, so the labels start at 2. Scan the grid row by row. A cell that still holds 1 belongs to an island with no label yet, so walk from it to every land cell joined to it, writing the label into each one and counting them.

Writing the label also marks a cell as done, because it no longer holds 1 and the scan passes over it. The sizes go into a list where the size of island 2 sits at position 2, island 3 at position 3, and so on, with two placeholder zeros at positions 0 and 1.

How does the walk reach every cell of an island? It keeps the cells it still has to visit in a stack, a pile where the cell put on last is the first taken off. It takes a cell off, adds one to the count, and puts on each neighbour that still holds 1. Because the newest cell is always taken next, the walk goes as deep as it can along one path before coming back. That order is called depth-first search, or DFS.

A neighbour gets its label when it goes on the stack, not when it comes off. Otherwise, a cell next to two land cells could be put on by both of them and counted twice.

Scoring each 0

Once every island has its label, how do we score a 0? A second scan looks at each 0 and collects the labels of its four neighbours in a HashSet, a Java collection that keeps each value only once. Water neighbours and cells outside the grid are skipped. The score is 1 for the filled cell plus the size of each label in the set.

A grid with no 0

What if there is nothing to fill, as in Example 3? The second scan then scores nothing. So the answer starts at the size of the largest island found while labelling, and the scores of the 0s can only raise it. A grid of only water works too: each 0 scores 1 on its own.

Optional: a recursive walk

Could the walk be shorter? Instead of a stack, the method that labels a cell can call itself for each of the four neighbours. That is fewer lines, but every call still in progress waits on the call stack, the small block of memory Java gives each thread for method calls, 1 MB by default on our JDK.

One winding island can make the calls go thousands deep. In our run, the recursive version labelled a 50 × 50 grid of 1s, but a 100 × 100 grid threw StackOverflowError. The stack in the code below is an ordinary Java object, so it grows in heap memory and handles a 500 × 500 grid.

Java Solution

The method largestIsland works in these steps:

  1. First, create size, a list holding the two placeholder zeros, and set label to 2 and best to 0. Then scan the grid with two loops, one inside the other: the outer loop moves r over the rows and the inner loop moves c over the columns.
  2. Each cell that still holds 1 starts a new island. paint labels the whole island with label and returns its size, which is added to size. Then label goes up by one, and best keeps the largest size so far, in case there is no 0.
  3. Inside paint, stack is an ArrayDeque used as a stack. The start cell is labelled and pushed. While stack is not empty, a cell is popped and area goes up by one. Each neighbour that still holds 1 is labelled and pushed, using the four moves in DIRS: down, up, right and left.
  4. Scan the grid a second time with the same two loops. For each 0, the set touching collects the labels of its neighbours, the values above 1. total starts at 1, adds the size of each label in touching, and raises best if it is bigger.
  5. When the second scan is done, return best.

The main method runs the three examples, the grid from the picture, a U-shaped island around one 0, a grid of only water and a 500 × 500 grid of 1s. Its helper run prints each grid before largestIsland writes labels into it.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MakingALargeIsland {

    private static final int[][] DIRS = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    public static int largestIsland(int[][] grid) {
        int n = grid.length;
        List<Integer> size = new ArrayList<>(List.of(0, 0)); // labels start at 2
        int label = 2;
        int best = 0;
        for (int r = 0; r < n; r++) {
            for (int c = 0; c < n; c++) {
                if (grid[r][c] == 1) {
                    int area = paint(grid, r, c, label++);
                    size.add(area);
                    best = Math.max(best, area);      // in case there is no 0 to fill
                }
            }
        }
        for (int r = 0; r < n; r++) {
            for (int c = 0; c < n; c++) {
                if (grid[r][c] != 0) {
                    continue;
                }
                Set<Integer> touching = new HashSet<>();  // each island counted once
                for (int[] d : DIRS) {
                    int nr = r + d[0];
                    int nc = c + d[1];
                    if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] > 1) {
                        touching.add(grid[nr][nc]);
                    }
                }
                int total = 1;                        // the filled cell itself
                for (int t : touching) {
                    total += size.get(t);
                }
                best = Math.max(best, total);
            }
        }
        return best;
    }

    // Writes label into every cell of the island at (r, c) and returns its size.
    private static int paint(int[][] grid, int r, int c, int label) {
        int n = grid.length;
        Deque<int[]> stack = new ArrayDeque<>();
        grid[r][c] = label;
        stack.push(new int[] {r, c});
        int area = 0;
        while (!stack.isEmpty()) {
            int[] cell = stack.pop();
            area++;
            for (int[] d : DIRS) {
                int nr = cell[0] + d[0];
                int nc = cell[1] + d[1];
                if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] == 1) {
                    grid[nr][nc] = label;             // label on push: never pushed twice
                    stack.push(new int[] {nr, nc});
                }
            }
        }
        return area;
    }

    private static void run(int[][] grid) {
        String shown = Arrays.deepToString(grid);     // before paint changes the grid
        System.out.println(shown + " -> " + largestIsland(grid));
    }

    public static void main(String[] args) {
        run(new int[][] {{1, 0}, {0, 1}});
        run(new int[][] {{1, 1}, {1, 0}});
        run(new int[][] {{1, 1}, {1, 1}});
        run(new int[][] {{1, 1, 0, 1}, {1, 0, 0, 1}, {0, 1, 1, 0}, {0, 1, 0, 0}});
        run(new int[][] {{1, 1, 1}, {1, 0, 1}, {0, 0, 0}});
        run(new int[][] {{0, 0}, {0, 0}});
        int[][] big = new int[500][500];
        for (int[] row : big) {
            Arrays.fill(row, 1);
        }
        System.out.println("500 x 500 grid of 1s -> " + largestIsland(big));
    }
}

Running it prints:

Output
[[1, 0], [0, 1]] -> 3
[[1, 1], [1, 0]] -> 4
[[1, 1], [1, 1]] -> 4
[[1, 1, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 0, 0]] -> 7
[[1, 1, 1], [1, 0, 1], [0, 0, 0]] -> 6
[[0, 0], [0, 0]] -> 1
500 x 500 grid of 1s -> 250000

[[1, 0], [0, 1]] gives 3, the two corner cells joined by either 0. [[1, 1], [1, 1]] gives 4 although the second scan finds no 0, because best already held the island's size from the labelling. The grid from the picture gives 7, the orange 0 joining islands 2 and 4.

Look at the U shape, [[1, 1, 1], [1, 0, 1], [0, 0, 0]]. Its one island of 5 touches the middle 0 from above, from the left and from the right, and the answer is 6 because touching holds label 2 only once. When we ran a version that adds a size for every land neighbour instead, it printed 16, which is 1 + 5 + 5 + 5.

The grid of only water gives 1, the filled cell on its own. The last line is one island of 250,000 cells, labelled by a single call to paint without trouble, because the cells waiting to be visited sit in stack, in heap memory, not on the call stack.

Complexity

The work is two scans of the grid, plus the walks that label the islands.

  • Time: O(n²), because a label replaces the 1 in each land cell, so all the walks together visit each of the n² cells once, and scoring a 0 checks only its four neighbours.
  • Space: O(n²), because stack can hold a large share of one big island's cells, and size holds about n²/2 entries when single land cells alternate with water like a chessboard.

The labelling walk on its own, finding the biggest island without filling anything, is Max Area of Island.