Simple Java Solution


  • 1
    Z
    public class Solution {
        public void solve(char[][] board) {
            if (board == null || board.length == 0) {
                return;
            }
    
            int m = board.length;
            int n = board[0].length;
    
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (i == 0 || j == 0 || i == m - 1 || j == n - 1) {
                        if (board[i][j] == 'O') {
                            BFS(board, i, j, m, n);
                        }
                    }
                }
            }
    
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (board[i][j] == 'O') {
                        board[i][j] = 'X';
                    } else if (board[i][j] == '1') {
                        board[i][j] = 'O';
                    }
                }
            }
        }
    
        public void BFS(char[][] board, int i, int j, int m, int n) {
            if (i < 0 || j < 0 || i >= m || j >= n || board[i][j] != 'O') {
                return;
            }
    
            board[i][j] = '1';
            if (i + 1 < m) {
                BFS(board, i + 1, j, m, n);
            }
            if (i > 1) {
                BFS(board, i - 1, j, m, n);
            }
            if (j + 1 < n) {
                BFS(board, i, j + 1, m, n);
            }
            if (j > 1) {
                BFS(board, i, j - 1, m, n);
            }
        }
    }
    

Log in to reply
 

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