# Clean and Easy-understanding Java solution using BFS

• ``````public void solve(char[][] board) {

if(board.length == 0) return;

for(int y = 0; y < board.length; y++) {
if(board[y][0] == 'O') {
markAll(board, 0, y, board[0].length, board.length);
}
if(board[y][board[0].length - 1] == 'O') {
markAll(board, board[0].length - 1, y, board[0].length, board.length);
}
}

for(int x = 0; x < board[0].length; x++) {
if(board[0][x] == 'O') {
markAll(board, x, 0, board[0].length, board.length);
}
if(board[board.length - 1][x] == 'O') {
markAll(board, x, board.length - 1, board[0].length, board.length);
}
}

for(int y = 0; y < board.length; y++) {
for(int x = 0; x < board[0].length; x++) {
if(board[y][x] == 'O') board[y][x] = 'X';
if(board[y][x] == '1') board[y][x] = 'O';
}
}

}

private void markAll(char[][] board, int x, int y, int xMax, int yMax){
if(x < 0 || x >= xMax || y < 0 || y >= yMax) return;

if(board[y][x] == 'O') board[y][x] = '1';
else return;

if(x - 1 > 0 && board[y][x - 1] == 'O')
markAll(board, x - 1, y, xMax, yMax);
if(x + 1 < xMax && board[y][x + 1] == 'O')
markAll(board, x + 1, y, xMax, yMax);
if(y - 1 > 0 && board[y - 1][x] == 'O')
markAll(board, x, y - 1, xMax, yMax);
if(y + 1 < yMax && board[y + 1][x] == 'O')
markAll(board, x, y + 1, xMax, yMax);
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.