Problem of the day
Given an ‘M’ x ‘N’ matrix ‘GRID’ containing ‘X’ and ‘O’, capture all the regions that are 4 directionally surrounded by ‘X’ and update the original 'GRID'.
A region is captured by flipping all ‘O’s to ‘X’s in that surrounding region.
Example:Input:
3 3
XXX
XOX
XXX
Output:
XXX
XXX
XXX
Explanation:
The ‘O’ is surrounded by ‘X’s in all directions, so it is captured and flipped.
The first line of the input contains an integer, ‘T’, denoting the number of test cases.
The First line of each test case contains two integers, ‘N’ and ‘M’ denoting the number of rows and columns in the ‘GRID’.
The next ‘N’ lines of each test case contain ‘M’ characters, ‘O’ or ‘X’.
Output format :
Modify the original ‘GRID’ by flipping the captured ‘O’s.
1 <= T <= 10
1 <= N,M <= 200
Time Limit: 1 sec
2
3 3
XXX
XOX
XXX
3 4
XXXO
XXOX
XOXX
XXX
XXX
XXX
XXXO
XXXX
XOXX
Test 1:
The ‘O’ is surrounded by ‘X’s in all directions, so it is captured and flipped.
Test 2:
The ‘O’ in the first row is only surrounded by 2 sides.
The ‘O’ in the second row is surrounded by all 4 sides, hence
flipped.
The ‘O’ in the third row is only surrounded by 3 sides.
2
3 3
XXX
XOX
XOX
3 4
OOXO
OXOX
OOXO
XXX
XOX
XOX
OOXO
OXXX
OOXO
The connected component including ‘O’s at the boundary of the GRID will never be captured.
The solution to the problem lies in marking all the connected components of ‘O’s which also touches the boundary of the GRID as they are not surrounded by ‘X’s from all 4 directions so they can not be captured.
This can be implemented by performing Depth First Search for every ‘O’ at the boundary of the GRID and marking them. Now we can reiterate through the GRID and change the unmarked ‘O’s to ‘X’s and remaining to ‘O’s .
The steps are as follows :
Void DFS ([char][] GRID , int x , int y)
Void capture([char][] GRID)
O( N x M ), Where N and M are the numbers of rows and columns.
The DFS is performed for every ‘O’ at the boundary, which would go to NxM cells only 1 time.
Hence the time complexity is O( N x M ).
O( 1 )
Since we are only updating the original GRID without using any extra space.
Hence the space complexity is O( 1 ).