X X X X
X O O X
X X O X
X O X X
X X X X
X X X X
X X X X
X O X X
class Solution {
public void solve(char[][] board) {
if (board == null || board.length == 0) {
return;
}
int m = board.length, n = board[0].length;
int[][] directions = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
for (int i = 0; i < m; i++) {
fill(board, i, 0, directions);
fill(board, i, n - 1, directions);
}
for (int j = 0; j < n; j++) {
fill(board, 0, j, directions);
fill(board, m - 1, j, directions);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == '#') {
board[i][j] = 'O';
}
else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
public void fill(char[][] board, int row, int col, int[][] directions) {
if (board[row][col] == 'O') {
board[row][col] = '#';
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[] {row, col});
while (!queue.isEmpty()) {
int[] cell = queue.remove();
int curRow = cell[0], curCol = cell[1];
for (int[] direction : directions) {
int nextRow = curRow + direction[0];
int nextCol = curCol + direction[1];
if (isValid(board, nextRow, nextCol)) {
board[nextRow][nextCol] = '#';
queue.add(new int[] {nextRow, nextCol});
}
}
}
}
}
public boolean isValid(char[][] board, int row, int col) {
return row >= 0 && row < board.length && col >= 0 && col < board[0].length && board[row][col] == 'O';
}
}
3. Time & Space Complexity