Share my brute force solution


  • 1
    J

    The solution is easy to understand.

    1. Transversal all the elements on the boundary, if it is 'O' change into 'Y'.

    2. Transversal all the elements, if it is 'O' change into 'X'. If it is 'Y' change into 'X'

      public class Solution {
      public void solve(char[][] board) {
      int row=board.length;
      if(row == 0) return;
      int col=board[0].length;
      Queue<Integer> xQueue=new LinkedList<Integer>();
      Queue<Integer> yQueue=new LinkedList<Integer>();
      for(int i=0;i<row;i++){
      if(board[i][0]=='O'){
      xQueue.add(i);
      yQueue.add(0);
      }
      if(board[i][col-1]=='O'){
      xQueue.add(i);
      yQueue.add(col-1);
      }
      }
      for(int i=0;i<col;i++){
      if(board[0][i]=='O'){
      xQueue.add(0);
      yQueue.add(i);
      }
      if(board[row-1][i]=='O'){
      xQueue.add(row-1);
      yQueue.add(i);
      }
      }
      while(!xQueue.isEmpty()){
      int x=xQueue.poll();
      int y=yQueue.poll();
      board[x][y]='Y';
      if(x>0&&board[x-1][y]=='O'){
      xQueue.add(x-1);
      yQueue.add(y);
      }
      if(x<row-1&&board[x+1][y]=='O'){
      xQueue.add(x+1);
      yQueue.add(y);
      }
      if(y>0&&board[x][y-1]=='O'){
      xQueue.add(x);
      yQueue.add(y-1);
      }
      if(y<col-1&&board[x][y+1]=='O'){
      xQueue.add(x);
      yQueue.add(y+1);
      }
      }
      for(int i=0;i<row;i++){
      for(int j=0;j<col;j++){
      if(board[i][j]=='O'){
      board[i][j]='X';
      }
      if(board[i][j]=='Y'){
      board[i][j]='O';
      }
      }
      }
      }
      }


Log in to reply
 

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