04. Replace O's with X's
The problem can be found at the following link: Question Link
My Approach
I've used a DFS approach to point out the regions of 'O' characters that were not completely 'X' surrounded.
To identify these regions, I have checked all the grid borders. If I encounter any 'O' character along the border, it indicates that the connected 'O' characters within this region is not entirely enclosed by 'X'. So, I label such 'O' characters as 'N'.
At last, I identify the 'O' characters that are entirely surrounded, and I replace them with 'X' and change 'N' to 'O' back.
The steps involved in implementing this:
I define a
dx
anddy
array to represent the four possible directions: up, down, left, and right.I create two helper functions:
isValid
checks if a given cell is within the bounds of the matrix.isBoundary
checks if a given cell is on the boundary of the matrix.
I use a recursive function
setNotClosed
to mark all connected 'O' characters as 'N' if they are not closed (not surrounded by 'X').In the
fill
function, I iterate through the entire matrix and whenever I encounter an 'O' on the boundary, I callsetNotClosed
to mark all connected 'O' characters as 'N'.Finally, I iterate through the entire matrix again and change 'O' to 'X' and 'N' back to 'O' to complete the transformation.
Time and Auxiliary Space Complexity
Time Complexity: The time complexity is
O(n * m)
, wheren
is the number of rows, and m is the number of columns for traversing all cells of grid.Auxiliary Space Complexity: The space complexity is
O(1)
as we don't use any additional data structures that depend on the input size.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated