leetcode--Surrounded Regions

来源:互联网 发布:python hmmlearn库 编辑:程序博客网 时间:2024/05/29 08:49

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 XX O O XX X O XX O X X

After running your function, the board should be:

X X X XX X X XX X X XX O X X
[java] view plain copy
  1. public class Solution {  
  2.     public void solve(char[][] board) {  
  3.         int rows = board.length;  
  4.         if(rows<=0return;   
  5.         int cols = board[0].length;  
  6.         if(cols<=0return;   
  7.         boolean flag[][] = new boolean[rows][cols];  
  8.         ArrayList<Integer> queue_x = new ArrayList<Integer>();  
  9.         ArrayList<Integer> queue_y = new ArrayList<Integer>();  
  10.         boolean OK = true;  
  11.         int[] dir_x = new int[]{-1,1,0,0};  
  12.         int[] dir_y = new int[]{0,0,-1,1};  
  13.         for(int i=0;i<rows;i++){  
  14.             for(int j=0;j<cols;j++){  
  15.                 if(board[i][j]=='O'&&!flag[i][j]){                    
  16.                     int low = 0;  
  17.                     int high = 1;  
  18.                     OK = true;  
  19.                     queue_x.add(i);  
  20.                     queue_y.add(j);                   
  21.                     while(low<high){                                               
  22.                         for(int k=0;k<4;k++){  
  23.                             int x = queue_x.get(low)+dir_x[k];  
  24.                             int y = queue_y.get(low)+dir_y[k];  
  25.                             if(x>=0&&x<rows&&y>=0&&y<cols){  
  26.                                 if(!flag[x][y]&&board[x][y]=='O'){  
  27.                                     queue_x.add(x);  
  28.                                     queue_y.add(y);  
  29.                                     flag[x][y]=true;  
  30.                                     high++;  
  31.                                 }                                 
  32.                             }else{  
  33.                                 OK = false;  
  34.                             }                                 
  35.                         }                     
  36.                         low++;  
  37.                     }  
  38.                     if(OK){  
  39.                         for(int k=0;k<queue_x.size();k++){  
  40.                             board[queue_x.get(k)][queue_y.get(k)] = 'X';  
  41.                         }                         
  42.                     }  
  43.                     queue_x.clear();queue_y.clear();  
  44.                 }  
  45.             }  
  46.         }         
  47.     }  
  48. }  


原文链接http://blog.csdn.net/crazy__chen/article/details/46524447

原创粉丝点击