Given a matrix of ‘O’ and ‘X’ if surrounded by 'X' (original) (raw)
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.
**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.