LeetCode | Surrounded Regions

题目:

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
Java代码如下:
注意:本方法通过广度优先搜索算法实现,通过一个堆栈存储遍历的结果。
package com.LeetCode.cheng1;
import java.util.Random;
import java.util.Stack;

public class Surrounded_Regions {

public static void main(String[] args) {
// TODO Auto-generated method stub
Random r = new Random(); 
 int [] [] num = new int [5] [5]; 
 for(int n=0;n<5;n++){ 
  for(int m=0;m<5;m++){ 
//随机产生0,1的二维数组
   num[n][m]=r.nextInt(2); 
   System.out.print(num[n][m]);
  } 
  System.out.println();
 } 
Stack<index> stack = new Stack<index>();
 for(int i=0;i<5;i++){
 if(num[i][0]==0){
 index index = new index(i, 0);
//2表示原来是0,经过遍历搜索过的元素.
 num[i][0]=2;
 num=index.check(num, stack);
 }
 if(num[i][4]==0){
 index index = new index(i, 4);
 num[i][4]=2;
 num= index.check(num, stack);
 }
 }
 for(int j=0;j<5;j++){
 if(num[0][j]==0){
 index index = new index(0, j);
 num[0][j]=2;
 num=index.check(num, stack);
 }
 if(num[4][j]==0){
 index index = new index(4, j);
 num[4][j]=2;
 num=index.check(num, stack);
 }
 }
  //将结果转化为题目要求的格式 
 for(int n=0;n<5;n++){ 
  for(int m=0;m<5;m++){ 
  if(num[n][m]==0)
  num[n][m]=1;   
  if(num[n][m]==2)
  num[n][m]=0;
  }   
 } 
  //打印结果
 System.out.println();
 for(int n=0;n<5;n++){ 
  for(int m=0;m<5;m++){  
   System.out.print(num[n][m]);
  } 
  System.out.println();
 } 
}
}

//将数组的地址作为index对象存入堆栈中
class index{
int x;
int y;
public index(int x, int y) {
super();
this.x = x;
this.y = y;
}

public int[][] check(int [] [] num,Stack<index> stack){
if(x+1<num.length && num[x+1][y]==0){

stack.push(new index(x+1, y));
}
if(0<x-1 && num[x-1][y]==0){

stack.push(new index(x-1, y));
}
if(0<y-1 && num[x][y-1]==0){

stack.push(new index(x, y-1));
}
if(y+1<num.length && num[x][y+1]==0){

stack.push(new index(x, y+1));
}
if(!stack.empty()){
num[stack.peek().x][stack.peek().y]=2;
num=stack.pop().check(num, stack);
}
return num;
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值