Problem Description
Given an m x n board containing letters 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's if the region is fully surrounded (i.e., none of its cells are on the board's border).
Key Insights
- Regions connected to the border are not captured.
- Use DFS/BFS from border 'O's to mark safe cells.
- After marking, flip all remaining 'O's to 'X' and then revert the marked cells back to 'O'.
Space and Time Complexity
Time Complexity: O(m * n)
Space Complexity: O(m * n) in the worst case due to recursion stack or queue storage for DFS/BFS
Solution
The solution involves two main steps. First, traverse the board's borders and run a DFS or BFS from any encountered 'O', marking it (e.g., using '') to indicate that it should not be flipped. Next, go through each cell in the board: flip any remaining 'O' (i.e., not marked safe) to 'X' and change the temporary marker '' back to 'O'. This approach ensures only the regions completely surrounded by 'X' are captured.
Code Solutions
Python:
JavaScript:
C++:
Java: