leetCode练习(130)

题目:Surrounded Regions

难度:medium

问题描述:

Given a 2D board containing 'X' and 'O' (the letter 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

解题思路:不被包围的区域就是有‘O’点在边界的区域。只要把所有边界的'O'点找出了,然后使用BFS,标记所有的未被包围的点,最后进行处理即可。

代码如下:(偷了个懒,对数组边界的判断直接使用了try catch ,效率很低~)

public class Solution {
    public void solve(char[][] board) {
        if(board==null||board.length<=1||board[0].length<=1){
	        return;
	     }
	     int row=board.length;
	     int colum=board[0].length;
	     Queue<int[]> queue=new ArrayDeque<>();
	     for(int i=0;i<colum-1;i++){
	    	 if(board[0][i]=='O'){
	    		 int[] temp=new int[2];
	    		 temp[0]=0;temp[1]=i;
	    		 queue.add(temp);
	    	 }
	     }
	     for(int i=0;i<row-1;i++){
	    	 if(board[i][colum-1]=='O'){
	    		 int[] temp=new int[2];
	    		 temp[0]=i;temp[1]=colum-1;
	    		 queue.add(temp);
	    	 }
	     }
	     for(int i=colum-1;i>=1;i--){
	    	 if(board[row-1][i]=='O'){
	    		 int[] temp=new int[2];
	    		 temp[0]=row-1;temp[1]=i;
	    		 queue.add(temp);
	    	 }
	     }
	     for(int i=row-1;i>=1;i--){
	    	 if(board[i][0]=='O'){
	    		 int[] temp=new int[2];
	    		 temp[0]=i;temp[1]=0;
	    		 queue.add(temp);
	    	 }
	     }
	     while(!queue.isEmpty()){
	    	 int[] a=queue.poll();
	    	 int x=a[0];
	    	 int y=a[1];
	    	 if(board[x][y]=='X'||board[x][y]=='i'){
	    		 continue;
	    	 }
	    	 board[x][y]='i';
	    	 try{
	 			if(board[x-1][y]=='O'){
	 				int[] temp=new int[2];
		    		temp[0]=x-1;temp[1]=y;
		    		queue.add(temp);
	 			}
	 		 	}catch(Exception e){
	 			 
	 		 	}
	    	 try{
		 			if(board[x+1][y]=='O'){
		 				int[] temp=new int[2];
			    		temp[0]=x+1;temp[1]=y;
			    		queue.add(temp);
		 			}
		 		 	}catch(Exception e){
		 			 
		 		 	}
	    	 try{
		 			if(board[x][y-1]=='O'){
		 				int[] temp=new int[2];
			    		temp[0]=x;temp[1]=y-1;
			    		queue.add(temp);
		 			}
		 		 	}catch(Exception e){
		 			 
		 		 	}
	    	 try{
		 			if(board[x][y+1]=='O'){
		 				int[] temp=new int[2];
			    		temp[0]=x;temp[1]=y+1;
			    		queue.add(temp);
		 			}
		 		 	}catch(Exception e){
		 			 
		 		 	}
	    	 
	     }
	     for(int i=0;i<row;i++){
	    	 for(int j=0;j<colum;j++){
	    		 if(board[i][j]=='X'){
	    			 continue;
	    		 }else{
	    			 if(board[i][j]=='i'){
	    				 board[i][j]='O';
	    			 }else{
	    				 board[i][j]='X';
	    			 }
	    		 }
	    	 }
	     }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值