medium +25 pts

Surrounded Regions

Flip all 'O's that are completely surrounded by 'X's to 'X'.

Write a function `capture_surrounded(grid)` that takes a 2D list of characters `grid` (M rows, N columns) where each cell is either `'X'` or `'O'. Modify the board **in place** so that every `'O'` that is **completely surrounded by `'X'`** is replaced by `'X'`. An `'O'` is considered *not surrounded* if it is on the border of the board or is connected (up/down/left/right) to any border `'O'`. Return the modified grid. The input grid is not empty (M, N ≥ 1). Your solution should work efficiently for boards up to 200×200.

Constraints

- 1 ≤ M, N ≤ 200 - Each cell contains exactly `'X'` or `'O'`. - You may modify the input list in place or return a new list, but the result must be a list of lists with the same dimensions.

Example

>>> capture_surrounded([['X','X','X','X'],['X','O','O','X'],['X','X','O','X'],['X','O','X','X']])
[['X','X','X','X'],['X','X','X','X'],['X','X','X','X'],['X','O','X','X']]
>>> capture_surrounded([['X']])
[['X']]
>>> capture_surrounded([['O','O'],['O','O']])
[['O','O'],['O','O']]
25 points ~30 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think of all 'O's that should remain as those connected to the border. Mark them first.
Use BFS or DFS starting from every border 'O' to mark safe 'O's.
After marking safe cells, change unmarked 'O's to 'X' and revert marked ones to 'O'.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.