Surrounded Regions
Surrounded Regions is LeetCode 130 (Medium). You get an m × n board of 'X' and 'O' cells and must change it in place.
- A region is a group of
'O'cells joined up, down, left or right. Diagonal cells do not join. - A region is surrounded when none of its cells is on the edge of the board. Replace every
'O'in a surrounded region with'X'. - Regions that touch the edge stay as they are.
The board can have 40,000 cells, so each cell should be handled a constant number of times.
- m == board.length
- n == board[i].length
- 1 <= m, n <= 200
- board[i][j] is 'X' or 'O'.
Intuition
Checking each region for a way out is awkward: you have to explore it fully before you know its fate. The opposite question is easy. A region escapes exactly when it contains a border cell, so start from the border and walk inward.
- Mark: every
'O'on the edge, and every'O'reachable from one, is safe. Write'#'on it. - Sweep: after the search, any
'O'still on the board was never reached, so it is surrounded and becomes'X'. Every'#'goes back to'O'.
The '#' doubles as the visited mark, so no extra grid is needed, and each cell is touched at most a few times.
When a grid question asks which cells cannot reach the edge, search from the edge instead and treat whatever stays unreached as the answer. Number of Enclaves counts those cells; here they are repainted.
Approach
Before reading on, decide which 'O' cells you can call safe without exploring anything. Then decide how to find the rest of the safe cells, and how to tell them apart from the cells to capture. Aim for O(m × n).
Mark every border O as safe
Scan the board and, for each 'O' in the first or last row or column, write '#' and add it to a queue. These cells touch the edge, so they can never be captured.
Spread safety with a breadth-first search
Pop a cell and look at the cell below, above, right and left of it. Each 'O' found is joined to the border through the popped cell, so mark it '#' and queue it. Marking it when it is queued means no cell enters the queue twice.
Sweep the board once
When the queue is empty, visit every cell. A '#' becomes 'O' again because the border reached it. An 'O' becomes 'X' because the search never reached it, so it is surrounded. 'X' stays 'X'.
Why the sweep is safe in one pass
Each cell is rewritten from its own value alone, and '#' and 'O' mean different things. A two-symbol version that flipped captured cells first would have no way to tell a kept 'O' from a captured one.
Code in Python, C++ and Java
Common pitfalls
Recursive DFS on a large board
def dfs(r, c):
board[r][c] = '#'
for nr, nc in neighbours:
dfs(nr, nc)q = deque() # or an explicit stack
One snake-shaped region can hold about 20,000 cells on a 200 × 200 board, and recursion goes one level per cell. Python's default limit is 1,000, so the DFS crashes with RecursionError; Java and C++ can overflow the stack too.
Seeding from only two sides
for c in range(n):
if board[0][c] == 'O': ...
if board[m - 1][c] == 'O': ...if (r in (0, m - 1) or c in (0, n - 1)) and board[r][c] == 'O':
Skipping the first and last columns loses every region that only touches the left or right edge. On [["X","X","X"],["O","O","X"],["X","X","X"]] the two O cells touch the left edge, yet this version captures them.
Counting diagonal cells as joined
for dr in (-1, 0, 1):
for dc in (-1, 0, 1): ...((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1))
On [["X","X","X"],["X","O","X"],["X","X","O"]] the middle O only touches the corner O diagonally, so it must be captured. With eight directions it is wrongly marked safe.
Edge cases
[["O","O","X"]]Every cell is on the border, so every O is marked safe and the board does not change.
[["X","X","X"],["X","O","X"],["X","X","X"]]The queue starts empty, the search does nothing, and the sweep captures every O on the board.
Complexity
'#' mark replaces a separate visited grid.Surrounded Regions FAQ
Should I use BFS or DFS?
Either works; both only need to visit every O joined to the border. BFS with a queue, or DFS with an explicit stack, never runs out of call stack. A recursive DFS is shorter to write but can run out of call stack on one large region.
Is this the same as Replace O's with X's?
Yes, it is the same task under another name. Some versions use other symbols or ask for a new board instead of changing it in place, but the border search and the sweep stay the same.
Can union-find solve it?
Yes. Join every O to its O neighbours and every border O to one extra node that stands for the edge. Afterwards, an O not in the edge node's set is captured. It is longer to write and no faster than the search.