#K64722. Capture Surrounded Regions
Capture Surrounded Regions
Capture Surrounded Regions
You are given an N × M grid (matrix) consisting of characters 'X' and 'O'. Your task is to capture all regions that are surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region.
An 'O' is not captured if it is on the border of the grid or if it is connected (vertically or horizontally) to an 'O' on the border. Use a depth-first search (DFS) approach starting from the boundary cells to mark safe cells, then flip the remaining unmarked 'O's to 'X'.
Formally, if we denote the matrix by \(mat\) with dimensions \(N\) rows and \(M\) columns, then for any cell \(mat[i][j]\) that is an 'O' and is not connected to any boundary 'O', change it into an 'X'.
inputFormat
The first line of input contains two space-separated integers \(N\) and \(M\), denoting the number of rows and columns in the matrix.
The following \(N\) lines each contain \(M\) space-separated characters (each character is either 'X' or 'O') representing the grid.
outputFormat
Output the modified matrix after capturing the surrounded regions. Print \(N\) lines, each containing \(M\) characters separated by a space.
## sample4 4
X X X X
X O X X
X O O X
X X X X
X X X X
X X X X
X X X X
X X X X
</p>