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'和'X'。所以可以用层次扫描结合图的搜索,
1:在层次扫描的时候,遇到'X'就标记为访问过,遇到'O'就:进行图的搜索,把所有和这个'O'相连的‘O'都访问一遍,在访问的过程当中,如果遇到
有'O'在边界上,那么所有的这些'O'都是不能变化的。如果搜索完之后,没有相连的'O'在边界上,那么这些’O‘都要进行改变,变为'X'。
2:搜索完之后,继续层次扫描,遇到访问过的格子就不理睬。
下面是代码,稍微有点长
/**
* Use boardth first search to find the region which is connected to the margin, or is all in x.
* If It is all in x, then marked it as 1, if It is connected to some margin, then doesn's add it
* in set.
*/
struct pos
{
int x;
int y;
pos(){}
pos(int x,int y): x(x),y(y){}
bool operator<(const pos& other) const
{
if(x == other.x)
{
return (y<other.y);
}else
{
return (x<other.x);
}
}
};
bool isVisit[1000][1000];
class Solution {
public:
void solve(vector<vector<char>> &board) {
int hight = board.size();
int xpos[4] = {-1,1,0,0};
int ypos[4] = {0,0,-1,1};
if(hight==0)
return ;
int width = board[0].size(),i,j,k,si,sj;
if(width==0)
return ;
memset(isVisit,false,sizeof(isVisit));
set<pos> res,temp;
set<pos>::iterator it;
queue<pos> myQueue;
pos tp;
// begin to scan this board
bool flag=true;
for(i=0;i<hight;i++)
{
for(j=0;j<width;j++)
{
if(board[i][j]=='O')
{
if(!isVisit[i][j])
{
flag = true;
isVisit[i][j] = true;
// if it is contains the region
if(i==0||j==0||i==hight-1||j==width-1)
{
flag = false;
}
pos p(i,j);
myQueue.push(p);
temp.insert(p);
// begin to use boardth first search to find the region
while(myQueue.size()>0)
{
tp = myQueue.front();
myQueue.pop();
// go up down left and right
for(k=0;k<4;k++)
{
si = tp.x+xpos[k];
sj = tp.y+ypos[k];
if((si>=0)&&(si<hight)&&(sj>=0)&&(sj<width))
{
if(!isVisit[si][sj]&&board[si][sj]=='O')
{
isVisit[si][sj] = true;
pos np(si,sj);
myQueue.push(np);
temp.insert(np);
if(flag)
{
if(si==0||sj==0||si==hight-1||sj==width-1)
{
flag = false;
}
}
}
}
}
}
//add this pos into the change pos, or change it directly
if(flag)
{
for(it = temp.begin();it!=temp.end();it++)
{
board[it->x][it->y] = 'X';
}
}
temp.clear();
}
}
}
}
return ;
}
};