Surrounded Regions - Problem
Imagine you're playing a strategic board game where you need to capture enemy territories! You have an m × n board filled with 'X' (your pieces) and 'O' (enemy pieces).
Your goal is to capture all surrounded enemy regions by flipping them to your side. An enemy region is considered surrounded if:
- It consists of connected
'O'cells (horizontally or vertically adjacent) - The entire region is completely enclosed by
'X'cells - No part of the region touches the board edges
When you capture a surrounded region, replace all 'O's in that region with 'X's in-place. Regions that touch the edges are safe and cannot be captured!
Example: A region of 'O's completely surrounded by 'X's gets flipped, but 'O's connected to the border remain unchanged.
Input & Output
example_1.py — Standard Case
$
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"]]
💡 Note:
The 'O' region in the center is completely surrounded and gets captured. The 'O' in the bottom row touches the border and remains safe.
example_2.py — Single Cell
$
Input:
board = [["X"]]
›
Output:
[["X"]]
💡 Note:
Board remains unchanged as there are no 'O' regions to capture.
example_3.py — Border Connected
$
Input:
board = [["O","O","O"],["O","X","O"],["O","O","O"]]
›
Output:
[["O","O","O"],["O","X","O"],["O","O","O"]]
💡 Note:
All 'O' cells are connected to the border, so none can be captured. The board remains unchanged.
Constraints
-
m == board.length -
n == board[i].length -
1 ≤ m, n ≤ 200 -
board[i][j]is'X'or'O' - Modify the board in-place
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code