Python
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board or not board[0]: return
excludePos = set()
rows = len(board)
cols = len(board[0])
def searchExclude(y, x):
if y = rows: return
if x = cols: return
if board[y][x] == "O" and (y,x) not in excludePos:
excludePos.add((y,x))
searchExclude(y-1, x)
searchExclude(y+1, x)
searchExclude(y, x-1)
searchExclude(y, x+1)
for y in range(rows):
searchExclude(y, 0)
searchExclude(y, cols-1)
for x in range(cols):
searchExclude(0, x)
searchExclude(rows-1, x)
for x in range(1, cols-1):
for y in range(1, rows-1):
if board[y][x] == "O" and (y,x) not in excludePos:
board[y][x] = "X"
C#
public class Solution {
public int rows;
public int cols;
public HashSet excludePos;
public void Solve(char[][] board) {
rows = board.Length;
if(rows == 0){return;}
cols = board[0].Length;
if(cols == 0){return;}
excludePos = new HashSet();
for(int y = 0; y < rows; y++)
{
SearchExcluded(board, y, 0);
SearchExcluded(board, y, cols-1);
}
for(int x = 0; x < cols; x++)
{
SearchExcluded(board, 0, x);
SearchExcluded(board, rows-1, x);
}
for(int y = 0; y < rows; y++)
{
for(int x = 0; x < cols; x++)
{
if(board[y][x] == 'O' && !excludePos.Contains((y, x)))
{
board[y][x] = 'X';
}
}
}
}
public void SearchExcluded(char[][] board, int y, int x) {
if(y = rows){return;}
if(x = cols){return;}
if(board[y][x] == 'O' && !excludePos.Contains((y, x)))
{
excludePos.Add((y, x));
SearchExcluded(board, y-1, x);
SearchExcluded(board, y+1, x);
SearchExcluded(board, y, x-1);
SearchExcluded(board, y, x+1);
}
}
}