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''O''O''O''X'
Example 1
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
Output: [["X"]]
The Idea
Picture each 'O''X'
Look at Example 1. The 'O''X'
The 'O'
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''O''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''S''X''X''S''O'
The board is a graph in disguise: each 'O'
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'
Remembering the safe cells
Where do we record that a cell is safe? On the board itself. A safe cell gets the letter 'S''O''X''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'ArrayDequepushpop
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'
Finishing the board
Once every spread is done, what is left? Any 'O''X''S''O'
Optional: spreading with recursion
The spread can also be written as a method that calls itself on each of the four neighbours:
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'StackOverflowErrorArrayDeque
Java Solution
The method solve
- First, read the board's size:
holds m androws holds n.cols - Call
on every border cell, with two loops: the first loop goes over each rowmarkSafe and tries its first and last cell, and the second loop goes over each columnr and tries its top and bottom cell.c - Inside
, return at once if the cell is not anmarkSafe . Otherwise mark it'O' and push it onto a new'S' namedArrayDeque .stack - While
is not empty, pop astack . For each of the four steps listed in the arraycell , work out the neighbour's rowMOVES and columnnr . If the neighbour is on the board and holdsnc , mark it'O' and push it.'S' - Back in
, a final pair of loops visits every cell, turning eachsolve into'O' and each'X' into'S' .'O'
The mainsolve'O'
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:
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, XOOXXXOXXXXXXOXX'O''O'
The fourth board shows the corner rule. The 'O'
Look at the last line: all 40000 cells of the 200 × 200 board are still 'O'markSafestackmarkStackOverflowError
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
at most once and then checks only its four neighbours, and the final pass reads each of the m × n cells once.stack - Space: O(m × n) in the worst case, because
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.stack
The same idea of spreading from the border solves