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.
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.
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.
- 1 <= R, C <= 200 - board[i][j] is 'X' or 'O'
An 'O' region is captured unless it touches the border. So the safe cells are exactly those the boundary can reach through 'O's — the same border-flood pattern as number of enclaves. Mark every border-connected 'O' (with a temporary symbol), then in one pass: flip the remaining 'O's (the surrounded ones) to 'X', and restore the marked cells back to 'O'. O(R·C).
Flooding from the border, rather than trying to detect "surrounded" per region, sidesteps the tricky part — a region is surrounded precisely when the border can't reach it.
“Which O's are safe?”
Those connected to a border O.
“In place?”
Yes — mark, then flip and restore.
I flood from every border O and mark it safe, then flip all unmarked O to X and restore the marks.
A region is captured exactly when the border can't reach it — O(R·C).
Worked example — board = [["X","X","X"],["X","O","X"],["X","X","X"]]
no border O -> flood marks nothing the central O is surrounded -> flipped to X result = all X
Only O's reachable from the boundary survive.
A temporary symbol separates safe O from captured O in one final pass.
One flood plus one sweep.
| Border DFS | Border BFS | |
|---|---|---|
| Flood via | recursion | queue |
| Time | O(R·C) | O(R·C) |
| Risk | deep recursion | none |
Both mark the same safe cells and capture the rest. Full code is in the Approaches selector below.
Key takeaway
Flood from every border 'O', marking safe cells; then flip unmarked 'O' to 'X' and restore the marks. O(R·C).
mark border-connected O as '#' sweep: O -> X ; '#' -> O