Surrounded Regions

medium

Given an R × C board of 'X' and 'O', capture all regions surrounded by 'X': flip every 'O' that is not connected (4-directionally) to a border 'O' into 'X'. Regions touching the boundary are safe. Return the modified board.

Hints

An 'O' is captured only if it is NOT connected to a border 'O'.
Flood from the border to mark all safe 'O's with a temporary symbol.
Then flip unmarked 'O' to 'X' and restore the temporary symbol to 'O'.

Common doubts

A region is surrounded exactly when the border can't reach it, so one border flood identifies all safe cells at once.
It distinguishes 'safe O' from 'capturable O' so a single final sweep can flip and restore correctly.
Identical border-flood pattern — enclaves counts the survivors, surrounded regions rewrites the captured ones.

Interview follow-ups

Yes — union border 'O's with a virtual 'safe' node; any 'O' not connected to it is captured.
Then no O is inherently safe; every enclosed region would be captured differently.

Fun facts

  • LeetCode 130 — the classic 'work from the boundary inward' problem.
  • The virtual-node union-find variant is a neat DSU exercise.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
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]]
The inner O-region is captured; the bottom O touches the border and survives.
Example 2
Input: board = [[O,O,O],[O,O,O],[O,O,O]]
Output: [[O,O,O],[O,O,O],[O,O,O]]
Every O touches the border, so nothing is captured.
Constraints

- 1 <= R, C <= 200 - board[i][j] is 'X' or 'O'

Solve this problem →