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
Understanding the Visualization
1
Scout the Coastline
Send scouts from all coastal positions to map enemy fortresses with sea access
2
Mark Safe Territories
All fortresses connected to the coast are marked as uncapturable
3
Launch the Assault
Attack and capture all remaining inland fortresses
4
Restore Coastal Markers
Remove temporary markings from coastal territories
Key Takeaway
๐ฏ Key Insight: Instead of checking if regions are surrounded, find which regions are NOT surrounded by starting from the borders!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code