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

How

scan the matrix from 1 to size-1.

find a big O ie. 'O'

from this position, do a  BFS

mark the position with result.

mark the resulted matrix.

repeat the above until no 'O' is found

replace marked dead 'O' with real 'O'.


My code below is the first glance, never optimized.

Code: 

void solve(vector<vector<char> > &board) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
	bool toBreak = false;
	bool isSurrounded = true;
	vector<int> processingXs;
	vector<int> processingYs;

	while(1){
		int i=0, sizei=0;;
		int j=0, sizej=0;
		// Find a big O
		for(i=1, sizei=board.size(); i<sizei-1; i++){

			for(j=1, sizej=board[i].size();j<sizej-1;j++){
				if(board[i][j] == 'O'){
					board[i][j] = 1;
					processingXs.push_back(i);
					processingYs.push_back(j);
					toBreak = true;
					break;
				}
			}
			if(toBreak){
				toBreak = false;
				break;
			}
		}//end find big o

		// no big o is found
		if(i>=sizei-1){
			break;
		}
		isSurrounded = true;
		//find all adjacent big Os and mark them
		for(int k=0; k<processingXs.size();k++){
			int x=processingXs[k];
			int y=processingYs[k];
			int left = x-1;
			int right = x+1;
			int top = y - 1;
			int bottom = y + 1;
			int cors[][2] = {
					{left, y},
					{x, top},
					{x, bottom},
					{right, y},
			};

			for(int l=0; l<4; l++){

				int xx = cors[l][0];
				int yy = cors[l][1];

				if(board[xx][yy]=='O'){
					if(xx>0&&xx<board.size()-1 && yy>0&&yy<board.size()-1){
						processingXs.push_back(xx);
						processingYs.push_back(yy);
						board[xx][yy]='1';
					}else{
						isSurrounded = false;
					}
				}

			}

		}

		char symbol = ' ';
		if(isSurrounded){
			symbol='X';
		}else{
			symbol='2';
		}

		for(int l=0; l<processingXs.size(); l++){
			int xx = processingXs[l];
			int yy = processingYs[l];
			board[xx][yy] = symbol;
		}
		processingXs.clear();
		processingYs.clear();

	}

	for(int xx=0; xx<board.size(); xx++){
		for(int yy=0; yy<board.size();yy++){
			if(board[xx][yy] == '2'){
				board[xx][yy] = 'O';
			}
		}
	}

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值