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); } } }