Surrounded Regions
Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #130
Given a board of 'X' and 'O', capture every region of 'O' that is completely surrounded by 'X' (4-directionally) by flipping it to 'X'. An 'O' region that touches the border is never captured. Modify board in place.
Example
text
X X X X X X X X
X O O X → X X X X
X X O X X X X X
X O X X X O X X (bottom O touches the border: safe)Hints
- Deciding "is this region surrounded?" directly is awkward. Ask the opposite question.
- Which O's are safe? Exactly those connected to an O on the border.
Approach
Reverse thinking:
- DFS from every
'O'on the border, marking the cells reached as safe (e.g.'#'). - Sweep the board: remaining
'O'→'X'(captured), and'#'→'O'(restored).
Every cell is touched a constant number of times: O(mn). The same "start from the boundary" trick solves Pacific Atlantic Water Flow and Number of Enclaves.
Complexity
Time: O(m·n). Space: O(m·n) worst-case stack.
Python solution
def solve(board):
if not board:
return
R, C = len(board), len(board[0])
stack = [(r, c) for r in range(R) for c in (0, C - 1)] + [(r, c) for c in range(C) for r in (0, R - 1)]
while stack:
r, c = stack.pop()
if 0 <= r < R and 0 <= c < C and board[r][c] == 'O':
board[r][c] = '#'
stack += [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]
for r in range(R):
for c in range(C):
board[r][c] = 'O' if board[r][c] == '#' else 'X'JavaScript solution
function solve(board) {
const R = board.length, C = board[0].length, stack = [];
for (let r = 0; r < R; r++) stack.push([r, 0], [r, C - 1]);
for (let c = 0; c < C; c++) stack.push([0, c], [R - 1, c]);
while (stack.length) {
const [r, c] = stack.pop();
if (r < 0 || c < 0 || r >= R || c >= C || board[r][c] !== 'O') continue;
board[r][c] = '#';
stack.push([r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]);
}
for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) board[r][c] = board[r][c] === '#' ? 'O' : 'X';
}