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
Output: 3
Explanation: changing either 0 joins the two single cells into an island of 3.
Example 2
Output: 4
Example 3
Output: 4
Explanation: there is no 0 to change.
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]]
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.
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 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
Java Solution
The method largestIsland
- First, create
, a list holding the two placeholder zeros, and setsize to 2 andlabel to 0. Then scan the grid with two loops, one inside the other: the outer loop movesbest over the rows and the inner loop movesr over the columns.c - Each cell that still holds 1 starts a new island.
labels the whole island withpaint and returns its size, which is added tolabel . Thensize goes up by one, andlabel keeps the largest size so far, in case there is no 0.best - Inside
,paint is anstack used as a stack. The start cell is labelled and pushed. WhileArrayDeque is not empty, a cell is popped andstack goes up by one. Each neighbour that still holds 1 is labelled and pushed, using the four moves inarea : down, up, right and left.DIRS - Scan the grid a second time with the same two loops. For each 0, the set
collects the labels of its neighbours, the values above 1.touching starts at 1, adds the size of each label intotal , and raisestouching if it is bigger.best - When the second scan is done, return
.best
The mainrunlargestIsland
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:
[[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]][[1, 1], [1, 1]]best
Look at the U shape, [[1, 1, 1], [1, 0, 1], [0, 0, 0]]touching
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 paintstack
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
can hold a large share of one big island's cells, andstack holds about n²/2 entries when single land cells alternate with water like a chessboard.size
The labelling walk on its own, finding the biggest island without filling anything, is