boolean[][] visited; int m; int n; int[][] move = {{0,1},{-1,0},{0,-1},{1,0}}; public void solve(char[][] board) { m = board.length; if(m==0) return; n = board[0].length; visited = new boolean[m][n]; for(int i= 0 ;i<m;i++){ for(int j=0;j<n;j++){ if(board[i][j] == 'O' && !visited[i][j]){ mark(i,j,board); } } } return; } private boolean mark(int i, int j, char[][] board) { visited[i][j] = true; boolean lable = false; if(i==m-1 || j==n-1 || i==0 || j==0) lable = true; for(int k=0; k<4; k++){ int newx = i + move[k][0]; int newy = j + move[k][1]; if(inarea(newx,newy) && !visited[newx][newy] && board[newx][newy]=='O'){ lable = mark(newx,newy,board) || lable ; } if(!lable) board[i][j] = 'X'; } return lable; } private boolean inarea(int i, int j) { return i>=0 && j>=0 && i<m && j<n; }