LeetCode #130 Medium

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.

Constraints
  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 200
  • board[i][j] is 'X' or 'O'.
graphsdfsbfsmatrix
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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).

1

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.

2

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.

3

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'.

4

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.

04

Code in Python, C++ and Java

▶1from collections import deque
▶2 
▶3class Solution:
▶4 def solve(self, board):
▶5 m, n = len(board), len(board[0])
▶6 q = deque()
▶7 for r in range(m):
▶8 for c in range(n):
▶9 if (r in (0, m - 1) or c in (0, n - 1)) and board[r][c] == "O":
▶10 board[r][c] = "#"
▶11 q.append((r, c))
▶12 
▶13 while q:
▶14 r, c = q.popleft()
▶15 for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
▶16 if 0 <= nr < m and 0 <= nc < n and board[nr][nc] == "O":
▶17 board[nr][nc] = "#"
▶18 q.append((nr, nc))
▶19 
▶20 for r in range(m):
▶21 for c in range(n):
▶22 board[r][c] = "O" if board[r][c] == "#" else "X"
01230123XXXXXOOXXXOXX#XXinside the ring is interior# = safequeue3, 1front1 border O → mark safe, queue
border Osrow 3, col 1first and last rows and columns
Every cell outside the dashed ring is on the border. An O there can never be surrounded, so it is marked # (safe) and queued. Any O joined to it is safe too, and the queue is how the search finds them.
01230123XXXXXOOXXXOXX#XXinside the ring is interior# = safequeueemptytake row 3, col 1 → look at its 4 sides
cellrow 3, col 1
queue left0
This cell is safe. Any O directly above, below, left or right of it is joined to the border through it, so each of the four sides is checked next. Diagonal cells are not neighbours.
01230123XXXXXOOXXXOXX#XXinside the ring is interior# = safequeueemptybelow is off the board → skip
neighbouroff the board
queue0 cells
There is no cell below of row 3, col 1, so the bounds check fails and nothing happens.
01230123XXXXXOOXXXOXX#XXinside the ring is interior# = safequeueemptyX above → skip
neighbourrow 2, col 1
queue0 cells
The cell at row 2, col 1 is X, a wall. The search cannot pass through it.
01230123XXXXXOOXXXOXX#XXinside the ring is interior# = safequeueemptyX to the right → skip
neighbourrow 3, col 2
queue0 cells
The cell at row 3, col 2 is X, a wall. The search cannot pass through it.
01230123XXXXXOOXXXOXX#XXinside the ring is interior# = safequeueemptyX to the left → skip
neighbourrow 3, col 0
queue0 cells
The cell at row 3, col 0 is X, a wall. The search cannot pass through it.
01230123XXXXXOOXXXOXX#XXinside the ring is interior# = safequeueemptyrow 0: no O here
captured0O not reached
kept0# back to O
This row has only X cells, so the sweep changes nothing visible here, but every cell is still read once.
01230123XXXXXXXXXXOXX#XXinside the ring is interior# = safequeueemptyrow 1: 2 O captured → X
captured2O not reached
kept0# back to O
The search is over, so an O that is still O was never reached from the border: it is surrounded and becomes X.
01230123XXXXXXXXXXXXX#XXinside the ring is interior# = safequeueemptyrow 2: 1 O captured → X
captured1O not reached
kept0# back to O
The search is over, so an O that is still O was never reached from the border: it is surrounded and becomes X.
01230123XXXXXXXXXXXXXOXXinside the ring is interior# = safequeueemptyrow 3: 1 safe cell back to O
captured0O not reached
kept1# back to O
Each # was reached from the border, so it survives and turns back into O.
01230123XXXXXXXXXXXXXOXXinside the ring is interior# = safequeueemptydone: 3 cells captured
captured3
Red cells were O but had no path of O cells to the edge, so they were captured. Green cells were joined to the border and stay O. Every cell was visited a constant number of times.
05

Common pitfalls

Recursive DFS on a large board

✗ Wrong
def dfs(r, c):
    board[r][c] = '#'
    for nr, nc in neighbours:
        dfs(nr, nc)
✓ Right
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

✗ Wrong
for c in range(n):
    if board[0][c] == 'O': ...
    if board[m - 1][c] == 'O': ...
✓ Right
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

✗ Wrong
for dr in (-1, 0, 1):
    for dc in (-1, 0, 1): ...
✓ Right
((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.

06

Edge cases

One row or one column, [["O","O","X"]]

Every cell is on the border, so every O is marked safe and the board does not change.

No O on the edge, [["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.

07

Complexity

Time
O(m × n)
Space
O(m × n)
Each cell is scanned once, queued at most once, and swept once. The queue is the only extra memory; the '#' mark replaces a separate visited grid.
08

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.