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
[[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
Output: 0
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.
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)rcarea
areaarea(grid, 3, 8)
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
Sinking changes the caller's grid. If the grid is still needed afterwards, pass a copy, or keep a separate boolean
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
Java Solution
The method maxAreaOfIsland
- First, set
to 0. It holds the largest area found so far, and it stays 0 if the grid has no land.best - Scan the grid with two loops, one inside the other. The outer loop moves
down the rows, and the inner loop movesr along the columns of rowc .r - When
is 1, it is the first cell of an island not measured yet. Callgrid[r][c] and keep the larger of its result andarea(grid, r, c) inbest .best - Inside
, return 0 if rowarea , columnr is outside the grid or not 1. Otherwise setc to 0, and return 1 plus the calls on the cells below, above, right and left.grid[r][c] - After the scan has passed every cell,
is the area of the largest island, and the method returns it.best
The main
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:
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 = 6land cells left in Example 1 afterwards = 0
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 = 1best
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
counts and sinks each land cell once, then checks it at most four more times from its neighbours.area - 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