广度优先搜索

43 篇文章 0 订阅
13 篇文章 0 订阅

130. Surrounded Regions

   
Total Accepted: 52330  Total Submissions: 324643  Difficulty: Medium
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
思路:广度优先搜索
我们知道边上的O不可能被包围,和O相通的O也不可能被X包围,我们就是要找出这样的情况并将其他的O设置为X,这些O不变
#include<iostream>
#include<vector>
#include<queue>

using namespace std;

void solve(vector<vector<char> >& board) {
	queue<pair<int,int> > q;
	int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
	if(board.size()==0)
		return;
	int lenX = board.size(), lenY = board[0].size();
	for(int i=0; i<lenX; i++){
		for(int j=0; j<lenY; j++){
			if(i==0||i==lenX-1||j==0||j==lenY-1){
				if(board[i][j]=='O'){
					q.push(make_pair(i,j));
				}
			}
		}
	}
	//BFS
	while(!q.empty()){
		pair<int,int> p=q.front();
		q.pop();
		int indX=p.first;
		int indY=p.second;
		board[indX][indY]='Y';
		for(int i=0;i<4;i++){
			int newX=indX+dx[i];
			int newY=indY+dy[i];
			if(newX>=0&&newX<lenX&&newY>=0&&newY<lenY&&board[newX][newY]=='O'){
				q.push(make_pair(newX,newY));
			}
		}
	}
	for(int i=0; i<lenX; i++){
		for(int j=0; j<lenY; j++){
			board[i][j]=(board[i][j]=='Y'?'O':'X');
				
		}
	}
	
}

int main(){
	
	return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值