Case 1: 'O's on the border
If an 'O'
is located directly on the border of the matrix (top row, bottom row, left column, or right column), it cannot be surrounded by 'X'
s. Therefore, any 'O'
on the border and all 'O'
s connected to it should not be converted to 'X'
. We mark these 'safe' regions with a temporary character, such as '#'
.
Case 2: 'O's connected to the border
These are internal 'O'
s that are directly or indirectly connected to border 'O'
s. For example, if (1, 1) is connected to (0, 1), and (0, 1) is a border 'O'
, then (1, 1) is also safe. During DFS/BFS from border 'O'
s, we traverse and mark all such connected 'O'
s as '#'
.
Case 3: Truly surrounded 'O's
After all border-connected 'O'
s have been marked, any remaining 'O'
in the matrix is truly surrounded by 'X'
s. These should be converted to 'X'
as they are not safe. This step is done in a final traversal where we check every cell:
- If it is
'O'
, we change it to 'X'
.
- If it is
'#'
, we change it back to 'O'
.
Final Matrix
The result is a matrix where all the 'O'
s that were truly surrounded by 'X'
s have been converted, and those connected to the border are left unchanged.