Wednesday, January 21, 2015

Surrounded Regions (LeetCode Breadth-first Search)

Question: Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X

Idea: For each 'O' at boundary, do breadth-first search to mark the reachable block as '#'. Then scan the matrix and mark all non-'#' blocks as 'X' and '#' blocks as 'O'.

Time: O(n^2) Space: O(n^2)

Code:
 public class Solution {  
   public class Block{  
     int x;  
     int y;  
     public Block(int x,int y)  
     {  
       this.x=x;  
       this.y=y;  
     }  
   }  
   public void solve(char[][] board) {  
     if(board.length==0||board[0].length==0)  
       return;  
     int m=board.length;  
     int n=board[0].length;  
     for(int j=0;j<n;j++)  
     {  
       if(board[0][j]=='O')  
         bfs(board,0,j);  
       if(board[m-1][j]=='O')  
         bfs(board,m-1,j);  
     }  
     for(int i=0;i<m;i++)  
     {  
       if(board[i][0]=='O')  
         bfs(board,i,0);  
       if(board[i][n-1]=='O')  
         bfs(board,i,n-1);  
     }  
     for(int i=0;i<m;i++)  
     {  
       for(int j=0;j<n;j++)  
       {  
         if(board[i][j]=='#')  
           board[i][j]='O';  
         else  
           board[i][j]='X';  
       }  
     }  
   }  
   public void bfs(char[][] board,int startX,int startY)  
   {  
     int m=board.length;  
     int n=board[0].length;  
     Queue<Block> queue=new LinkedList<Block>();  
     queue.offer(new Block(startX,startY));  
     while(queue.isEmpty()==false)  
     {  
       int queueSize=queue.size();  
       for(int i=0;i<queueSize;i++)  
       {  
         Block cur=queue.poll();  
         if(board[cur.x][cur.y]=='O')  
         {  
           board[cur.x][cur.y]='#';  
           if(cur.x+1<m&&board[cur.x+1][cur.y]=='O')  
             queue.offer(new Block(cur.x+1,cur.y));  
           if(cur.x-1>=0&&board[cur.x-1][cur.y]=='O')  
             queue.offer(new Block(cur.x-1,cur.y));  
           if(cur.y+1<n&&board[cur.x][cur.y+1]=='O')  
             queue.offer(new Block(cur.x,cur.y+1));  
           if(cur.y-1>=0&&board[cur.x][cur.y-1]=='O')  
             queue.offer(new Block(cur.x,cur.y-1));  
         }  
       }  
     }  
   }  
 }  

No comments:

Post a Comment