遍历,遇到O,则push到数组,然后搜寻附近的O,如果遇到边界的O,则表明该区域不是封闭的;如果最后不再找到O,说明该区域封闭,将该区域内元素全改为X。每次处理一个O后都将其改为.,避免重复处理。最后需要将.还原成O。代码如下
-
class Solution {
-
public:
-
-
void solve(vector<vector<char>> &board) {
-
// IMPORTANT: Please reset any member data you declared, as
-
// the same Solution instance will be reused for each test case.
-
vector<vector<int>> region;
-
-
if(board.size()<2||board[0].size()<2) return;
-
-
for(int i=1;i<board[0].size()-1;i++)
-
{
-
for(int j=1;j<board.size()-1;j++)
-
{
-
if(board[j][i]=='O')
-
{
-
board[j][i]='.';
-
region.clear();
-
region.push_back(vector<int>(2,j));
-
region[region.size()-1][1]=i;
-
bool flag=true;
-
int oldlen=0;
-
int newlen=region.size();
-
while(oldlen!=newlen)
-
{
-
for(int k=oldlen;k<newlen;k++)
-
{
-
int row=region[k][0],coloum=region[k][1];
-
if(row==0||row==board.size()-1||coloum==0||coloum==board[0].size()-1) {flag=false;};
-
if(row>0&&board[row-1][coloum]=='O')
-
{region.push_back(vector<int>(2,row-1));region[region.size()-1][1]=coloum;board[row-1][coloum]='.';}
-
if(row<board.size()-1&&board[row+1][coloum]=='O')
-
{region.push_back(vector<int>(2,row+1));region[region.size()-1][1]=coloum;board[row+1][coloum]='.';}
-
if(coloum>0&&board[row][coloum-1]=='O')
-
{region.push_back(vector<int>(2,row));region[region.size()-1][1]=coloum-1;board[row][coloum-1]='.';}
-
if(coloum<board[0].size()-1&&board[row][coloum+1]=='O')
-
{region.push_back(vector<int>(2,row));region[region.size()-1][1]=coloum+1;board[row][coloum+1]='.';}
-
}
-
oldlen=newlen;
-
newlen=region.size();
-
}
-
if(true==flag)
-
{
-
for(int k=0;k<region.size();k++)
-
{
-
int row=region[k][0], coloum=region[k][1];
-
board[row][coloum]='X';
-
}
-
}
-
}
-
}
-
}
-
for(int i=0;i<board[0].size();i++)
-
{
-
for(int j=0;j<board.size();j++)
-
{
-
if(board[j][i]=='.')
-
{
-
board[j][i]='O';
-
}
-
}
-
}
-
}
-
};
阅读(210) | 评论(0) | 转发(0) |