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''0'
Example 1
Output: 1
Example 2
Output: 3
The Idea
Picture a map seen from above and cut into squares. Each square is either land, marked '1''0'
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.
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'
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
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''1''1'
Remembering visited cells
How does the walk avoid going round in circles between neighbours? Writing '0'
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
Optional: walking with a queue
Each sinksinkStackOverflowError
To avoid the deep chain, put the cells still to visit in a queue, such as an ArrayDeque
Java Solution
The method numIslands
- First, set
to 0. Then go over the grid with two loops, one inside the other: the outer loop movescount down the rows, and the inner loop movesr along the columns of rowc .r - When
isgrid[r][c] , add 1 to'1' and callcount to turn the whole island into water.sink(grid, r, c) returns at once if (sink ,r ) is outside the grid or does not holdc . Otherwise it sets'1' togrid[r][c] and calls itself on the cells below, above, right and left.'0'- When both loops are done, return
.count
The helper gridchar[][]showmain
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:
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: 1sinkislands: 3
The grid labelled "Corners only", 1001islands: 2islands: 1islands: 0'1'
Sinking is what makes the count one per island, not one per cell. A version that adds 1 for every '1'
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
turns each land cell into water once, with at most four more quick checks from its neighbours.sink - 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
calls can be as long as the number of cells.sink
To measure the size of each island instead of counting them, see