Surrounded Regions

Medium#130grid

You get a board of X and O. A group of O cells joined by sides is surrounded when none of them lies on the edge of the board; turn every surrounded O into X, in place. Our board has 4 rows: X X X X X, X O X O X, X O X O O, X X O X X — the answer is X X X X X, X X X O X, X X X O O, X X O X X: the two O on the left are surrounded, the three on the right reach the edge at (2, 4), and (3, 2) is on the edge itself.

input
board: an m × n grid of 'X' and 'O'. Cells are neighbours when they share a side; neighbouring 'O's make up a region.
returns
Nothing: change board in place, turning every 'O' of a region that does not reach the edge of the board into 'X'. A region with a cell on the edge stays as it is.
constraints
  • 1 ≤ m, n ≤ 100, board[i].length = n
  • board[i][j] is 'X' or 'O'
our 14 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {character[][]} board
 * @return {void} Do not return anything, modify board in-place instead.
 */
function solve(board) {

}
Ctrl ↵
format
reset

saved in this browser

14 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more depth-first search (dfs) problems

Pattern “Depth-first search (DFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.