Number of Closed Islands
Count the islands of land in a grid of 0s and 1s that never reach the edge of the grid.
Given a grid of m rows and n columns where 0 is land and 1 is water, count its closed islands. Land cells that sit next to each other up, down, left or right belong to the same island. An island is closed when none of its cells lies on the edge of the grid, so water surrounds it on every side.
Example 1
Output: 2
Example 2
Output: 1
Explanation: rows and columns are counted from 0. Only the land at row 1, column 2 is closed. All other land touches the edge.
The Idea
Read the grid as a map seen from above, with each 0 a square of land and each 1 a square of water. Many grid puzzles use 1 for land, so this one is the other way round. From a land square you may walk up, down, left or right onto more land, never diagonally. An island is all the land one such walk can reach.
The map shows nothing beyond its edge, so an island that reaches the edge is not known to be surrounded by water. Such an island is open, and it does not count. Look at the picture below. It shows Example 2, and from now on a cell is written as (row, column).
The cells labelled "land on an open island" form two islands. The left one is (0,0), (0,1), (1,0) and (2,0), and the right one is (0,3), (0,4), (1,4) and (2,4). Both lie on the edge: from (0,0), a step up leaves the grid, which the arrow labelled "a step off the grid" shows. The cell labelled "the closed island", (1,2), is different. Each of its four orange arrows lands on water, so the answer is 1.
So how can a program tell an open island from a closed one? Looking at a single cell is not enough. Take the grid whose row 1 reads 0 0 0 0 0 1, with water above and below. The cell (1,3) has no edge next to it, yet its island runs left all the way to (1,0) on the edge. Whether an island is open depends on all of its cells.
So explore each island completely: start from any one of its cells and keep stepping onto land neighbours until no new land is left. While exploring, watch every step. If even one step leaves the grid, the island is open. If none does, it is closed. Marking each explored cell also makes sure the same island is never counted twice.
The grid is really a graph here: each land cell is a point, and two points are linked when their cells are neighbours. In Example 2, (0,0), (1,0) and (2,0) form a chain of linked points, while (1,2) is a point with no links at all. Counting closed islands means counting the groups of linked points that stay away from the edge.
Solution Approach
Turning that idea into code means settling four things: how to find each island once, how to explore an island, how to notice the edge, and why the exploration must not stop early. A shorter recursive way to explore, and why it failed on a large grid, comes last.
Finding each island once
Where does each exploration start? One slow plan asks, for every land cell on its own, whether some walk from it reaches the edge. All the cells of one island would then repeat the same walk. Instead, scan the grid row by row, and let the first land cell the scan meets start the exploration of its island.
The exploration turns every cell it reaches into water. The scan then never meets that island again, and no separate array of visited cells is needed. This changes the input grid, so a caller that still needs the grid should pass a copy.
Exploring an island with a queue
How do we reach every cell of the island? Keep a line of cells still to look at. Take the cell at the front, try its four steps, and add each land neighbour at the back. A line where cells join at the back and leave from the front is a queue. The code keeps the island's waiting cells in an ArrayDequeofferpoll
Because the queue hands out cells in the order they were found, the exploration spreads from the start cell like a ripple: first all land one step away, then two steps away, and so on. Exploring in that order is called breadth-first search, or BFS, because it covers the full width of one step before going further.
A neighbour is turned into water at the moment it joins the queue, not when it leaves. Two cells waiting in the queue can share a neighbour, and the early change keeps that neighbour from joining twice.
Noticing the edge
How does the exploration notice the edge? For each of the four steps, it works out the neighbour's row and column. If either one falls outside the grid, the current cell is on the edge, so a flag named closed
Exploring to the end
Once closed
Optional: exploring with recursion
The exploration can also be a method that calls itself on each of the four neighbours and returns whether its part of the island stayed away from the edge. It is shorter, but every call that has not finished yet waits on the thread's call stack, which has a fixed size. In our run, a 100 × 100 grid of land inside a ring of water made the recursive version throw StackOverflowError
Java Solution
The method closedIsland
- First, set
to 0 and scan the grid with two loops, one inside the other: the outer loop movescount down the rows, and the inner loop movesr along the columns.c - When
is 0, callgrid[r][c] , and add 1 toexploreIsland(grid, r, c) if it returns true.count - Inside
, turn the start cell into water, put it into a newexploreIsland namedArrayDeque , and setqueue to true.closed - While
is not empty, poll aqueue . For each of the four moves kept in the arraycell (down, up, right, left), work out the neighbour's rowSTEPS and columnnr . If they fall outside the grid, setnc to false. Otherwise, if the neighbour is land, turn it into water and offer it toclosed .queue - When
is empty, the whole island has become water, andqueue returnsexploreIsland . Once the scan inclosed ends, it returnsclosedIsland .count
The main
import java.util.ArrayDeque;
import java.util.Deque;
public class NumberOfClosedIslands {
private static final int[][] STEPS = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
// 0 is land, 1 is water.
public static int closedIsland(int[][] 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] == 0 && exploreIsland(grid, r, c)) {
count++;
}
}
}
return count;
}
// Turns the whole island at (row, col) into water; true if it never touched the edge.
private static boolean exploreIsland(int[][] grid, int row, int col) {
Deque<int[]> queue = new ArrayDeque<>();
grid[row][col] = 1; // explored land becomes water
queue.offer(new int[] {row, col});
boolean closed = true;
while (!queue.isEmpty()) {
int[] cell = queue.poll();
for (int[] step : STEPS) {
int nr = cell[0] + step[0];
int nc = cell[1] + step[1];
if (nr < 0 || nr >= grid.length || nc < 0 || nc >= grid[0].length) {
closed = false; // a step off the grid: this island is open
} else if (grid[nr][nc] == 0) {
grid[nr][nc] = 1;
queue.offer(new int[] {nr, nc});
}
}
}
return closed;
}
static void run(int[][] grid) {
for (int[] row : grid) {
StringBuilder line = new StringBuilder(" ");
for (int v : row) {
line.append(v).append(' ');
}
System.out.println(line.toString().stripTrailing());
}
System.out.println("closed islands: " + closedIsland(grid));
System.out.println();
}
public static void main(String[] args) {
run(new int[][] {{1, 1, 1, 1, 1}, {1, 0, 1, 0, 1}, {1, 1, 1, 1, 1}});
run(new int[][] {{0, 0, 1, 0, 0}, {0, 1, 0, 1, 0}, {0, 1, 1, 1, 0}});
run(new int[][] {{0, 1, 0}});
run(new int[][] {{1, 1, 1, 1, 1}, {1, 0, 0, 0, 1}, {1, 0, 1, 0, 1},
{1, 0, 0, 0, 1}, {1, 1, 1, 1, 1}});
run(new int[][] {{1, 1, 1, 1, 1, 1}, {0, 0, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1}});
int[][] big = new int[100][100];
for (int i = 0; i < 100; i++) {
big[0][i] = big[99][i] = big[i][0] = big[i][99] = 1;
}
System.out.println("100 x 100, all land inside a ring of water: " + closedIsland(big));
}
}
Running it prints:
1 1 1 1 1
1 0 1 0 1
1 1 1 1 1
closed islands: 2
0 0 1 0 0
0 1 0 1 0
0 1 1 1 0
closed islands: 1
0 1 0
closed islands: 0
1 1 1 1 1
1 0 0 0 1
1 0 1 0 1
1 0 0 0 1
1 1 1 1 1
closed islands: 1
1 1 1 1 1 1
0 0 0 0 0 1
1 1 1 1 1 1
closed islands: 0
100 x 100, all land inside a ring of water: 1
Example 1 gives closed islands: 2
The single row 0 1 0
The grid whose row 1 reads 0 0 0 0 0 1closed islands: 1
The last line comes from the 100 × 100 grid: its 98 × 98 = 9,604 land cells are one closed island, the same grid that overflowed the call stack of the recursive version.
Complexity
The scan looks at every cell, and each land cell goes through the queue once.
- Time: O(m × n), because the scan checks each of the m × n cells once, and each land cell joins the queue once and tries its four steps once, after which it is water.
- Space: O(m × n) in the worst case, because the queue can hold many cells of a large island at the same time, while the grid itself records which cells are explored.
Counting the land cells of such islands, instead of the islands, is