Skip to problem
←

Capture Surrounded Regions

Medium 0 attempts

Given a board of 'O' and 'X' cells, replace every enclosed region of 'O' cells with 'X'.

Cells are connected only through shared sides—up, down, left, or right. Diagonal contact does not connect regions. A region is enclosed if none of its cells can reach the board’s outer edge through connected 'O' cells.

Keep all border-connected 'O' cells and all existing 'X' cells unchanged. Return the resulting board.

Function contract

board is a nonempty rectangular matrix containing the characters 'O' and 'X'.

Output: Return the updated board. You may modify board in place; the returned matrix is checked.

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: The three interior O cells are captured. The O on the bottom edge remains unchanged.

Example 2

Input
board = [["O"]]
Output
[["O"]]
Constraints
  • 1 <= m, n <= 200
  • board[i][j] is 'X' or 'O'
Topics

Border Flood Fill

Only regions connected to a border survive. Mark all such cells safe with an iterative flood fill, then capture unmarked O cells.

javascript
function captureRegions(board) {
  if (!board.length) return board;
  const rows = board.length,
    cols = board[0].length,
    stack = [];
  function visit(r, c) {
    if (r >= 0 && r < rows && c >= 0 && c < cols && board[r][c] === 'O') {
      board[r][c] = 'S';
      stack.push([r, c]);
    }
  }
  for (let r = 0; r < rows; r++) {
    visit(r, 0);
    visit(r, cols - 1);
  }
  for (let c = 0; c < cols; c++) {
    visit(0, c);
    visit(rows - 1, c);
  }
  while (stack.length) {
    const [r, c] = stack.pop();
    visit(r + 1, c);
    visit(r - 1, c);
    visit(r, c + 1);
    visit(r, c - 1);
  }
  for (let r = 0; r < rows; r++)
    for (let c = 0; c < cols; c++) board[r][c] = board[r][c] === 'S' ? 'O' : 'X';
  return board;
}

Time: O(rows × cols) | Space: O(rows × cols)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript