![]() |
VOOZH | about |
Given a matrix grid[ ][ ] where each cell contains either 'O' or 'X'. We have to replace all the ‘O’s with ‘X’s if they are surrounded by ‘X’s on all sides.
An 'O' is considered surrounded if it cannot reach the boundary of the matrix by moving up, down, left, or right through adjacent 'O' cells.
Examples:
Input: grid[][] = [['X', 'O', 'X', 'X', 'X', 'X'],
['X', 'O', 'X', 'X', 'O', 'X'],
['X', 'X', 'X', 'O', 'O', 'X'],
['O', 'X', 'X', 'X', 'X', 'X'],
['X', 'X', 'X', 'O', 'X', 'O'],
['O', 'O', 'X', 'O', 'O', 'O']]Output: [['X', 'O', 'X', 'X', 'X', 'X'],
['X', 'O', 'X', 'X', 'X', 'X'],
['X', 'X', 'X', 'X', 'X', 'X'],
['O', 'X', 'X', 'X', 'X', 'X'],
['X', 'X', 'X', 'O', 'X', 'O'],
['O', 'O', 'X', 'O', 'O', 'O']]Explanation: The 'O's at positions (1,4), (2,3), and (2,4) are completely surrounded by 'X' on all sides, so they are replaced with 'X'. All other 'O's remain unchanged because they are connected to the boundary ‘O’s,
Input: grid[][] = [['X', 'X', 'X', 'X']
['X', 'O', 'X', 'X']
['X', 'O', 'O', 'X']
['X', 'O', 'X', 'X']
['X', 'X', 'O', 'O']]Output: [['X', 'X', 'X', 'X']
['X', 'X', 'X', 'X']
['X', 'X', 'X', 'X']
['X', 'X', 'X', 'X']
['X', 'X', 'O', 'O']]Explanation: The 'O's at positions (1,1), (2,1), (2,2), (3,1) is fully surrounded by
'X'and is converted to'X'; the'O's at (4,2) and (4,3) remain because they touch the matrix boundary.
The main idea is to use the Flood-Fill algorithm. The key difference here is that an 'O' is not replaced by an 'X' if it is part of a region connected to the boundary. To achieve this, we temporarily mark all the 'O's that are connected to any boundary 'O' using any traversal algorithm. After marking, we traverse the entire grid — any 'O' that is not marked is completely surrounded and can be safely converted into 'X'.
X O X O X X X O X X X X X X X X X X O X X X X X X X X O X O O O X O O O
Time Complexity: O(m x n), where n is the number of rows and m is the number of columns.
Auxiliary Space: O(m x n), as implicit stack is used due to recursive call