Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding
Ninjas X Naukri.com

Last Updated: 14 Jan, 2021

Moderate

```
1. Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the matrix is not flipped to 'X'.
2. Any ‘O’ or group of connected ‘O’ are said to be surrounded by ‘X’ when all cells touching the boundary of the group of ‘O’ must contain ‘X’.
```

```
The first line of the input contains an integer ‘T’ denoting the number of test cases.
The next 2 * T lines describe the ‘T’ test cases.
The first line of each test case contains two space-separated positive integers ‘N’ and ‘M’ denoting the number of the rows and columns in a matrix respectively.
In the next ‘N’ lines of each test case, the ith line contains a string of length ‘M’ containing either ‘X’ or ‘O’.
```

```
For each test case, print N lines each line containing M characters denoting the matrix element at position MATRIX[i][j] where i and j are the indices of the 2 - D array.
The output of each test case will begin from a new line.
```

```
You do not need to print anything, it has already been taken care of. Just implement the given function.
```

```
1 <= T <= 50
1 <= N <= 10 ^ 4
1 <= M <= 10 ^ 4
1 <= N * M <= 10 ^ 4
Where ‘T’ is the number of test cases, ‘N’ is the number of rows, ‘M’ is the number of columns.
Time Limit: 1 sec
```

- We will run two nested loops to traverse each cell of the matrix.
- For each cell containing ‘O’, we perform DFS in which we go to all adjacent neighbors containing ‘O’.
- The DFS function will tell us whether from this cell we can reach the boundary or not. If there is a way to reach the boundary from any of the neighbor cells of the current cell then this current cell can also reach the boundary through the neighbor cell. Hence this cell can’t be part of a region.
- If there is no way to reach the boundary then the current cell will be changed to ‘X’.

- We can use the same previous approach to speed up our DFS brute force approach. so Instead of checking for each cell, we can also check how many Os are reachable by the Os present on the boundary.
- We use a 2D boolean visited array of size NxM. We traverse on all four boundaries of the matrix if the current cell containing ‘O’ is marked false ( means unvisited ) then we perform DFS from this cell.
- We traverse on all possible neighboring elements containing ‘O’ if some cell is marked false ( means unvisited ) we marked it as true in our visited array. We don’t traverse the cells which are already visited.
- After performing DFS for each boundary the cells which are marked true in the visited array it means that this cell is reachable by some cell containing ‘O’ present on the boundary so this cell won’t be a part of the capture region. The cells which are marked false are not reachable to the boundary so we flip them ‘X’.