Surrounded Regions

Turn every group of 'O' cells that cannot reach the edge of the board into 'X', by marking the safe cells from the border inward.

A board of m rows and n columns holds the letters 'X' and 'O', with at most 200 rows and 200 columns. 'O' cells that sit next to each other up, down, left or right belong to the same region. A region is surrounded when none of its cells lies on the edge of the board. Change every 'O' of every surrounded region to 'X', in place, and leave all other cells as they are.

Example 1
Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
Explanation: rows and columns are counted from 0. The 'O' in row 3, column 1 is on the edge, so it stays. The other three 'O' cells form a surrounded region and become 'X'.
Example 2
Input: board = [["X"]]
Output: [["X"]]
Solution

The Idea

Picture each 'O' as an open square you can step on, and each 'X' as a wall. From an open square you may step up, down, left or right onto another open square, never diagonally. A group of open squares is trapped when no walk from it ever gets to the edge of the board. Trapped groups are filled in with walls.

Look at Example 1. The 'O' cells at row 1, column 1 and row 1, column 2 sit side by side, and the one at row 2, column 2 sits right below the second. From now on a cell is written as (row, column), so these three are (1,1), (1,2) and (2,2). They form one region. Every step out of it hits an 'X', so it is trapped.

The 'O' at (3,1) is a region of its own. It touches (2,2) only at a corner, which does not join them. It is on the bottom row, so it is already at the edge and stays.

So how do we decide, for each region, whether it is trapped? One way is to explore each region from the inside, keep a list of its cells, and check whether any of them lies on the edge. It works, but it means carrying every region's list around until its answer is known.

Turn the question around. A region escapes exactly when one of its cells is on the edge. So start at the 'O' cells on the edge and spread inward through neighbouring 'O' cells. Every cell the spread reaches is safe. Every 'O' it never reaches belongs to a surrounded region. Look at the picture below.

Example 1 in three boards with rows and columns 0 to 3. The light blue cells are the border. Marking from the border turns the O at (3,1) into S. The final pass turns the O cells at (1,1), (1,2) and (2,2) into X and turns S back into O.

The light blue cells are the border: the first and last row and column. In the board labelled "2. after marking from the border", the only 'O' on the border, (3,1), has become 'S', for safe. Its neighbours (2,1), (3,0) and (3,2) are all 'X', so the spread stops there. The three orange cells were never reached, and in "3. after the final pass" they are 'X' while 'S' is 'O' again.

The board is a graph in disguise: each 'O' cell is a point, and two points are connected when the cells are neighbours. Spreading from a border cell is a walk through that graph, and the cells it reaches are everything connected to the border.

Solution Approach

Turning that idea into code means settling four things: where the spreading starts, how to remember which cells are safe, how to reach every cell joined to a safe one, and how to finish the board. The spread can also be written as a recursive method, which is shorter but fails on big boards.

Where the spreading starts

Which cells start a spread? Every 'O' on the border. One loop goes down the rows and tries the first and last cell of each row, and a second loop goes along the columns and tries the top and bottom cell of each column. A corner is tried twice, which does no harm, because the second try finds it already marked.

Remembering the safe cells

Where do we record that a cell is safe? On the board itself. A safe cell gets the letter 'S', which is neither 'O' nor 'X'. That needs no extra array, and it also stops the spread from entering a cell twice, because the spread only steps onto cells that still hold 'O'.

Reaching every cell joined to a safe cell

How does the spread find every connected cell? It keeps a pile of cells still to look at. It takes the most recently added cell off the pile, checks its four neighbours, and adds each neighbour that still holds 'O'. A pile where the last cell in is the first one out is a stack. The code keeps the pile of cells in Java's ArrayDeque, adding a cell with push and taking the newest one with pop.

Because the newest cell is always handled first, the spread runs as far as it can in one direction before it comes back to older cells. Walking a graph in that order is called depth-first search, or DFS for short.

A neighbour is marked 'S' at the moment it is pushed, not when it is popped. Two cells on the pile can share a neighbour, and the early mark makes the second one skip it, so each cell is pushed at most once.

Finishing the board

Once every spread is done, what is left? Any 'O' still on the board was never reached, so it is surrounded and becomes 'X'. Every 'S' goes back to 'O'. One pass over all the cells does both.

Optional: spreading with recursion

The spread can also be written as a method that calls itself on each of the four neighbours:

Java
static void mark(char[][] b, int r, int c) {
    if (r < 0 || r >= b.length || c < 0 || c >= b[0].length || b[r][c] != 'O') {
        return;
    }
    b[r][c] = 'S';
    mark(b, r + 1, c);
    mark(b, r - 1, c);
    mark(b, r, c + 1);
    mark(b, r, c - 1);
}

It is shorter, but each call that has not finished waits on the thread's call stack, the memory where Java keeps unfinished method calls. Each thread gets 1 MB of it by default. On a board full of 'O', the calls go thousands deep. In our run, a 100 × 100 board worked, while 150 × 150 and 200 × 200 threw StackOverflowError. The ArrayDeque keeps its cells in ordinary heap memory, so a 200 × 200 board is no problem for it.

Java Solution

The method solve works in these steps:

  1. First, read the board's size: rows holds m and cols holds n.
  2. Call markSafe on every border cell, with two loops: the first loop goes over each row r and tries its first and last cell, and the second loop goes over each column c and tries its top and bottom cell.
  3. Inside markSafe, return at once if the cell is not an 'O'. Otherwise mark it 'S' and push it onto a new ArrayDeque named stack.
  4. While stack is not empty, pop a cell. For each of the four steps listed in the array MOVES, work out the neighbour's row nr and column nc. If the neighbour is on the board and holds 'O', mark it 'S' and push it.
  5. Back in solve, a final pair of loops visits every cell, turning each 'O' into 'X' and each 'S' into 'O'.

The main method prints each board before and after solve. It tries both examples, a region that reaches the edge through a long path, cells that touch only at corners, a board with every cell on the border, and a 200 × 200 board full of 'O'.

Java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

public class SurroundedRegions {

    private static final int[][] MOVES = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    public static void solve(char[][] board) {
        int rows = board.length;
        int cols = board[0].length;
        for (int r = 0; r < rows; r++) {          // left and right columns
            markSafe(board, r, 0);
            markSafe(board, r, cols - 1);
        }
        for (int c = 0; c < cols; c++) {          // top and bottom rows
            markSafe(board, 0, c);
            markSafe(board, rows - 1, c);
        }
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                if (board[r][c] == 'O') {
                    board[r][c] = 'X';            // never reached from the border: captured
                } else if (board[r][c] == 'S') {
                    board[r][c] = 'O';            // safe: back to 'O'
                }
            }
        }
    }

    // Marks the 'O' at (r, c) and every 'O' joined to it as 'S' (safe).
    private static void markSafe(char[][] board, int r, int c) {
        if (board[r][c] != 'O') {
            return;                               // an 'X', or already marked
        }
        Deque<int[]> stack = new ArrayDeque<>();
        board[r][c] = 'S';
        stack.push(new int[] {r, c});
        while (!stack.isEmpty()) {
            int[] cell = stack.pop();
            for (int[] move : MOVES) {
                int nr = cell[0] + move[0];
                int nc = cell[1] + move[1];
                if (nr >= 0 && nr < board.length && nc >= 0 && nc < board[0].length
                        && board[nr][nc] == 'O') {
                    board[nr][nc] = 'S';          // mark on push, so no cell is pushed twice
                    stack.push(new int[] {nr, nc});
                }
            }
        }
    }

    static char[][] board(String... rows) {
        char[][] b = new char[rows.length][];
        for (int i = 0; i < rows.length; i++) {
            b[i] = rows[i].toCharArray();
        }
        return b;
    }

    static void run(String... rows) {
        char[][] b = board(rows);
        solve(b);
        for (int i = 0; i < b.length; i++) {
            System.out.println(rows[i] + "  ->  " + new String(b[i]));
        }
        System.out.println();
    }

    public static void main(String[] args) {
        run("XXXX", "XOOX", "XXOX", "XOXX");                    // Example 1
        run("X");                                               // Example 2
        run("XXXX", "XOOX", "XOXX", "XOXX");                    // region leaves through (3,1)
        run("XXXXX", "XOXXX", "XXOXX", "XXXOX");                // corners touch, cells do not join
        run("OO", "OO");                                        // every cell on the border

        char[][] big = new char[200][200];
        for (char[] row : big) {
            Arrays.fill(row, 'O');
        }
        solve(big);
        long left = Arrays.stream(big).mapToLong(r -> new String(r).chars()
                .filter(ch -> ch == 'O').count()).sum();
        System.out.println("200 x 200 board of 'O': " + left + " cells still 'O'");
    }
}

Running it prints:

Output
XXXX  ->  XXXX
XOOX  ->  XXXX
XXOX  ->  XXXX
XOXX  ->  XOXX

X  ->  X

XXXX  ->  XXXX
XOOX  ->  XOOX
XOXX  ->  XOXX
XOXX  ->  XOXX

XXXXX  ->  XXXXX
XOXXX  ->  XXXXX
XXOXX  ->  XXXXX
XXXOX  ->  XXXOX

OO  ->  OO
OO  ->  OO

200 x 200 board of 'O': 40000 cells still 'O'

In the board of Example 1, XOOX and XXOX both become XXXX, while the bottom row XOXX keeps its 'O'. In the third board nothing changes. Its 'O' at (3,1) is on the bottom row, and the path up through (2,1) and (1,1) to (1,2) joins all four cells to the edge, so the spread marks every one of them safe.

The fourth board shows the corner rule. The 'O' at (3,3) is on the bottom row and stays. The one at (2,2) touches it only at a corner, so it is captured, and so is (1,1). In the 2 × 2 board every cell is on the border, so nothing can be captured.

Look at the last line: all 40000 cells of the 200 × 200 board are still 'O'. Every one of them is joined to the border, so the first call to markSafe, at (0,0), marks the whole board through stack. The recursive mark threw StackOverflowError on a board of this size.

Complexity

The work is the spreading from the border plus one final pass over the board, for a board of m rows and n columns.

  • Time: O(m × n), because each cell is pushed onto stack at most once and then checks only its four neighbours, and the final pass reads each of the m × n cells once.
  • Space: O(m × n) in the worst case, because stack can hold a large share of the cells when one region covers most of the board, while the safe marks themselves live on the board and cost nothing extra.

The same idea of spreading from the border solves Number of Enclaves, which counts the land cells of a grid that cannot reach its edge instead of filling them in.