Surrounded Regions

本文介绍了一个算法,用于在二维矩阵中翻转所有被'X'包围的'O'元素,实现矩阵区域的捕获。通过使用广度优先搜索(BFS),算法能够高效地识别并处理这些区域。

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
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct point
{
	int x;
	int y;
	point(int idx,int idy):x(idx),y(idy){}
};

queue<point*> Q;
void IsCircle(int high,int row,vector<vector<char>> &board)
{
	if (high>=0&&high<board.size()&&row>=0&&row<board[0].size()&&board[high][row]=='O'){
		board[high][row]='L';
		Q.push(new point(high,row));
	}
}
void BFS(int high,int row,vector<vector<char>> &board)
{
	IsCircle(high,row,board);	
	while (!Q.empty())
	{
		point* p = Q.front();
		Q.pop();
		IsCircle((p->x)+1,p->y,board);
		IsCircle((p->x)-1,p->y,board);
		IsCircle(p->x,p->y+1,board);
		IsCircle(p->x,p->y-1,board);
	}
}
void solve(vector<vector<char>> &board) { 

	if (board.empty() || board[0].size() == 0) {  
		return;  
	}  
	int high = board.size();
	int row  = board[0].size();
	for (int x = 0;x!=row;++x){
		BFS(0,x,board);
		BFS(high-1,x,board);
	}
	for (int y = 0;y!=high;++y){
		BFS(y,0,board);
		BFS(y,row-1,board);
	}
	for (int i=0;i!=high;++i)
	{
		for (int j=0;j!=row;++j )
		{
			board[i][j]=board[i][j]=='L'?'O':'X';
		}
	}
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值