Number of Enclaves

Count the land cells in a grid of land and sea that have no way to walk off the border.

Given a grid where 1 is land and 0 is sea, count the land cells from which you cannot walk off the grid. From a land cell you may step to the land cell above, below, left or right of it, but not diagonally. From a land cell on the border of the grid, you may also step off the grid. In the examples, (1,2) means row 1, column 2, both counted from 0.

Example 1
Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation: (1,0) is on the border. The three cells (1,2), (2,1) and (2,2) are trapped.
Example 2
Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation: all the land is joined to (0,1), which is on the border.
Solution

The Idea

Picture a map drawn on squared paper, where each square is either land or sea. A walker on land can step to the next land square north, south, east or west, but cannot swim. From a square on the border of the map, the walker can step off the map. A patch of land with no way off the map is called an enclave, and the problem asks how many land squares lie in enclaves.

Look at the picture below, which draws both examples as grids. In Example 1, the 1 at row 1, column 0 is on the left border, so it walks straight off, as the arrow shows. The three 1s at (1,2), (2,1) and (2,2) are joined to each other, but every square around them is sea. They are the orange cells, labelled "trapped land: an enclave", and there are 3 of them.

Example 1 and Example 2 as 4 by 4 grids with row and column numbers. In Example 1 the land at row 1, column 0 walks off the left border, and the land at (1,2), (2,1) and (2,2) is trapped. In Example 2 the land at (2,2) walks up through (1,2) and (0,2) and off the top border.

Example 2 shows that a cell away from the border is not trapped just because of where it sits. The 1 at (2,2) is not on the border, yet it can step up to (1,2), then to (0,2), and off the top of the grid. Every 1 in Example 2 is teal in the picture, "land joined to the border: can walk off", so the answer is 0.

So the real question for each land cell is whether a chain of land steps leads from it to a border cell. Land cells joined by such steps form a patch, usually called an island, and every cell of one island gets the same answer. Either the island reaches the border, and all of its cells can walk off, or it does not, and all of them are trapped.

That suggests turning the search around. Instead of starting at each land cell and looking for the border, start at the land on the border and walk inward. Every land cell reached that way can walk off. Remove all of them, and the land that is left is exactly the trapped land.

Moving from a cell to its neighbours and on to theirs is a search through a graph: the land cells are its points, and two land cells that share a side are connected.

Solution Approach

Turning that idea into code means settling three things: where the walks start, how one walk spreads through an island, and how to count the land that is left. A simpler plan, a separate search from every land cell, shows what the idea saves.

Searching from every land cell

What if each land cell runs its own search for the border? It works, but cells of the same island repeat the same search. A grid with m rows and n columns has m × n cells, and one search can cover most of them, so the total work can grow to about (m × n)² steps.

Where the walks start

Which cells start a walk? Every cell of the first row, the last row, the first column and the last column. A start cell that is sea simply does nothing.

Removing only the land that sits on the border is not enough, because islands reach inward. In Example 2, clearing just the border cells (0,1) and (0,2) leaves (1,2) and (2,2) standing, and the count comes out as 2 instead of 0. The walk has to follow each island all the way in.

Spreading through an island

How does one walk reach a whole island? A method sink(grid, r, c) handles one cell. If (r, c) is outside the grid or is sea, it returns. Otherwise it turns the cell into sea and calls itself on the four neighbours: below, above, right and left.

Each call follows its first neighbour as deep into the island as it can go before it comes back to try the next neighbour. This order of search is called depth-first search (DFS), and here it reaches every land cell that is joined to the starting cell.

Turning a cell into sea also marks it as done. A later call that lands on the same cell sees a 0 and returns, so no cell is handled twice and no separate "visited" grid is needed. The price is that the input grid is changed, so a caller who still needs it should pass a copy.

Counting the land that is left

Once every walk from the border has finished, what is left? Only trapped land is still 1, and all sea is 0. Adding up every cell of the grid therefore gives the number of trapped land cells.

Java Solution

The method numEnclaves works in these steps:

  1. First, read the size of the grid: m rows and n columns.
  2. Start a walk from every border cell with two loops, one after the other. The first loop moves r down the rows and calls sink on column 0 and column n - 1 of each row. The second loop moves c across the columns and calls sink on row 0 and row m - 1.
  3. Each call sink(grid, r, c) returns at once when (r, c) is outside the grid or not land. Otherwise it sets grid[r][c] to 0 and calls itself on the cells below, above, right and left.
  4. When both border loops are done, go through the grid with two more loops, one over the rows and one inside it over the cells of a row, adding each cell to count, and return count.

The main method runs both examples, a grid of a single land cell, and a 5 × 5 grid where some land touches only at corners. A helper, run, prints the count and then the grid as numEnclaves left it, row by row.

Java
public class NumberOfEnclaves {

    // 1 = land, 0 = sea
    public static int numEnclaves(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        for (int r = 0; r < m; r++) {          // left and right columns
            sink(grid, r, 0);
            sink(grid, r, n - 1);
        }
        for (int c = 0; c < n; c++) {          // top and bottom rows
            sink(grid, 0, c);
            sink(grid, m - 1, c);
        }
        int count = 0;                         // every 1 still standing is trapped
        for (int[] row : grid) {
            for (int cell : row) {
                count += cell;
            }
        }
        return count;
    }

    // Turns the land cell at (r, c), and all land joined to it, into sea.
    private static void sink(int[][] grid, int r, int c) {
        if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != 1) {
            return;                            // off the grid, sea, 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 void run(String name, int[][] grid) {
        int trapped = numEnclaves(grid);
        System.out.println(name + ": " + trapped + " trapped, grid afterwards:");
        for (int[] row : grid) {
            StringBuilder sb = new StringBuilder("  ");
            for (int cell : row) {
                sb.append(cell).append(' ');
            }
            System.out.println(sb.toString().stripTrailing());
        }
    }

    public static void main(String[] args) {
        run("Example 1", new int[][] {{0, 0, 0, 0}, {1, 0, 1, 0}, {0, 1, 1, 0}, {0, 0, 0, 0}});
        run("Example 2", new int[][] {{0, 1, 1, 0}, {0, 0, 1, 0}, {0, 0, 1, 0}, {0, 0, 0, 0}});
        run("Single cell", new int[][] {{1}});
        run("Diagonal neighbours", new int[][] {
            {1, 0, 0, 0, 0},
            {1, 1, 1, 0, 0},
            {0, 0, 1, 0, 0},
            {0, 1, 0, 1, 0},
            {0, 0, 0, 0, 0}});
    }
}

Running it prints:

Output
Example 1: 3 trapped, grid afterwards:
  0 0 0 0
  0 0 1 0
  0 1 1 0
  0 0 0 0
Example 2: 0 trapped, grid afterwards:
  0 0 0 0
  0 0 0 0
  0 0 0 0
  0 0 0 0
Single cell: 0 trapped, grid afterwards:
  0
Diagonal neighbours: 2 trapped, grid afterwards:
  0 0 0 0 0
  0 0 0 0 0
  0 0 0 0 0
  0 1 0 1 0
  0 0 0 0 0

Look at the grid printed after Example 1. The 1 that stood at row 1, column 0 is now 0, while the three 1s at (1,2), (2,1) and (2,2) are still there, so the count is 3. After Example 2 the grid holds only 0s: the walk that started at (0,1) on the top row spread to (0,2) and then down column 2 to (2,2).

The single cell [[1]] sits in the first and last row at once, so the border loops sink it and the count is 0. In the last grid, the island that starts at (0,0) runs through (1,0), (1,1) and (1,2) down to (2,2), and all of it is sunk. The 1s at (3,1) and (3,3) touch (2,2) only at a corner, which is not a step, so they stay and the count is 2.

Complexity

The work is the walks from the border plus one last pass over the grid, and no cell is turned into sea twice.

  • Time: O(m × n), because each land cell is sunk the first time a walk reaches it, later calls on it return at once, and the counting loops read each of the m × n cells once.
  • Space: O(m × n) in the worst case, because the chain of unfinished sink calls can be as long as one winding island joined to the border, while the grid itself serves as the record of visited cells.

Counting whole trapped islands instead of trapped cells is Number of Closed Islands.