You are given an m x n matrix board containing letters 'X' and 'O', capture regions that are surrounded:
'O' cell.'X' cells if you can connect the region with 'X' cells and none of the region cells are on the edge of the board.To capture a surrounded region, replace all 'O's with 'X's in-place within the original board. You do not need to return anything.
Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
Output:
Explanation:
In the above diagram, the bottom region is not captured because it is on the edge of the board and cannot be surrounded.
Input: board = [["X"]]
Output: [["X"]]
m == board.lengthn == board[i].length1 <= m, n <= 200board[i][j] is 'X' or 'O'.The problem can be approached using DFS to explore connected regions. The idea is to identify regions of 'O's connected to the boundary, which cannot be surrounded. All other 'O's can be flipped to 'X' as they are enclosed.
Instead of using DFS to solve the problem, we can use BFS. Using BFS helps to avoid the potential maximum recursion depth reached issue seen with DFS, especially with large matrices.
Union-Find can be applied to efficiently manage connections. We can think of each cell as a node, and connect boundary 'O's to a dummy node as they can't be surrounded. All other unconnected 'O's are converted to 'X'.