如今有一個僅包含‘X’和‘O’的二維板,請捕獲全部的被‘X’包圍的區域 捕獲一個被包圍區域的方法是將被包圍區域中的全部‘O’變成‘X’ 例如 X X X X↵X O O X↵X X O X↵X O X

public class Solution {
    public void solve(char[][] board) {
        
        if(board == null || board.length <= 1 || board[0].length <= 1){
            return;
        }
        int rows = board.length;
        int columns = board[0].length;
      
        //第一列和最後一列爲0
        for(int i = 0; i < rows; i++){
            if(board[i][columns-1]=='O'){
                checkBox(board,i,columns-1);
            }
            if(board[i][0]=='O'){
                checkBox(board,i,0);
            }
            
        }
        //第一行和最後一行爲0
        for(int j = 0 ; j < columns; j++){
            if(board[0][j] == 'O'){
                checkBox(board,0,j);
            }
            if(board[rows-1][j]=='O'){
                checkBox(board,rows-1,j);
            }
        }
       
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < columns; j++){
                if( 'O' == board[i][j] ){ 
                    board[i][j] = 'X';
                 }
                if( 'B' == board[i][j] ){ 
                    board[i][j] = 'O';
                 }
            }
        }
    }
    public void checkBox(char[][] board, int row, int column){
        if( row < 0 || row >= board.length || column < 0 || column >= board[0].length ){
            return;
        }
        if(board[row][column]=='O'){
            board[row][column]='B';
        }
        if(column < board[0].length-2 && board[row][column+1]=='O'){
            checkBox(board,row,column+1);
        }
        if(column >1 && board[row][column-1]=='O'){
            checkBox(board,row,column-1);
        }
        if(row < board.length-2 && board[row+1][column]=='O'){
            checkBox(board,row+1,column);
        }
        if(row >1 && board[row-1][column]=='O'){
            checkBox(board,row-1,column);
        }
    }
}
相關文章
相關標籤/搜索