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
Input: grid = [[1,1,1,1,1],[1,0,1,0,1],[1,1,1,1,1]]
Output: 2
Example 2
Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
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.
Solution

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).

Example 2 as a grid of 3 rows and 5 columns. The land in the left and right columns forms two open islands that touch the edge; from (0,0) a step goes off the grid. The land cell at (1,2) has water on all four sides and is the closed island.

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 ArrayDeque, calling offer to add a cell at the back and poll to take one from the front.

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 becomes false. If the neighbour is inside the grid and is land, it joins the queue. Water needs nothing.

Exploring to the end

Once closed is false, the answer for this island is known, so why not stop right there? Because the cells still in the queue, and the land beyond them, would stay land. The scan would meet them later and judge them as a new island, one that may never touch the edge.

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. The queue version below counts that grid without trouble.

Java Solution

The method closedIsland works in these steps:

  1. First, set count to 0 and scan the grid with two loops, one inside the other: the outer loop moves r down the rows, and the inner loop moves c along the columns.
  2. When grid[r][c] is 0, call exploreIsland(grid, r, c), and add 1 to count if it returns true.
  3. Inside exploreIsland, turn the start cell into water, put it into a new ArrayDeque named queue, and set closed to true.
  4. While queue is not empty, poll a cell. For each of the four moves kept in the array STEPS (down, up, right, left), work out the neighbour's row nr and column nc. If they fall outside the grid, set closed to false. Otherwise, if the neighbour is land, turn it into water and offer it to queue.
  5. When queue is empty, the whole island has become water, and exploreIsland returns closed. Once the scan in closedIsland ends, it returns count.

The main method prints each grid with its count: both examples, a single row, a ring of land around one water cell, an island that starts on the edge and runs inward, and a 100 × 100 grid.

Java
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:

Output
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, one for each single land cell in row 1. In Example 2 the count is 1: the scan meets (0,0) first and explores the left island, which is open, then (0,3) and the right island, which is open too, and finally (1,2), which is closed.

The single row 0 1 0 gives 0, because both of its land cells lie on the edge. The 5 × 5 grid gives 1: its eight land cells form a ring around the water at (2,2), and water inside an island neither splits it nor opens it.

The grid whose row 1 reads 0 0 0 0 0 1 is the check for exploring to the end, and it gives 0. The scan starts at (1,0), whose step left leaves the grid. We also ran a copy that returns false at that moment, and it printed closed islands: 1 for this grid. Its cells (1,2), (1,3) and (1,4) were still land and passed for a closed island.

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 Number of Enclaves.