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
Surrounded Regions - DFS Approach INPUT BOARD X X X X X O O X X X O X X O X X Surrounded O Edge O (Safe) X cells 4x4 board with regions ALGORITHM STEPS 1 Find Edge O's Scan all 4 borders 2 DFS from Edges Mark safe O's as '#' 3 Capture Surrounded O --> X (flip) 4 Restore Safe # --> O (restore) DFS Traversal O --> # --> O Edge-connected = Safe Time: O(m*n) | Space: O(m*n) FINAL RESULT X X X X X X X X X X X X X O X X Captured (O-->X) Safe (unchanged) OK - 3 cells captured! 1 edge O preserved Key Insight: Instead of finding surrounded regions directly, find the SAFE regions first! Any O connected to the border cannot be captured. Use DFS from all border O's to mark safe cells, then flip everything else. This "reverse thinking" simplifies the problem - mark safe, then capture the rest! TutorialsPoint - Surrounded Regions | DFS Approach
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