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
๐Ÿฐ Kingdom Defense StrategyKingdom Territory๐ŸฐEnemy๐ŸฐSafe๐ŸฐEnemy๐ŸฐSafeCoastline๐ŸŒŠ Coastal fortresses receive naval support and remain safeโš”๏ธ Inland fortresses get captured by your forces
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!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
98.5K Views
High Frequency
~15 min Avg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen