130. Surrounded Regions
- Total Accepted: 76047
- Total Submissions: 425973
- Difficulty: Medium
- Contributor: LeetCode
Given a 2D board containing 'X'
and 'O'
(the letter O), capture all regions surrounded by 'X'
.
A region is captured by flipping all 'O'
s into 'X'
s in that surrounded region.
解题思路:该题的思路是不难想到的,就是没有被X包围的O有两种情况:1.O位于边界上,此时不可能被包围;2.O与边界上的O相连(上下左右)
所以可以先遍历边界找到O放入队列然后对队列中的O进行BFS,标记搜到的O,最后遍历矩阵对未标记的O进行替换。时间复杂度为O(n*m)。
解题过程中犯的错误:1.重大错误就是一开始选择标记O的方式是另开一个同等大小的数组unchanged来记录O是否被标记,此时因为逻辑不够严谨,开始写的代码是每次标记队列弹出一个元素才修改unchanged的值导致可能会出现死循环(无法跳出while循环,因为可能还未修改unchanged的值之前又加入了重复的元素),修改方法为每次加入新元素之后就立马修改unchanged。
2.while循环中的判断条件忘记写unchanged[x]==0(逻辑的不严谨)
3.查询网上资料发现更好的方法是不用开辟新数组而是将遍历到的O修改为其他的值(节省空间也不容易犯错)
代码为
class Solution {
public:
void solve(vector<vector<char>>& board) {
int move_x[4]={0,1,0,-1};
int move_y[4]={1,0,-1,0};
int row=board.size();
if(row==0)
return ;
//cout<<row<<endl;
int column=board[0].size();
int unchanged[row][column];
memset(unchanged,0,sizeof(unchanged));
queue<pair<int,int> > ans;
for(int i=0;i<row;i++)
{
//cout<<"zhixing"<<endl;
if(i==0||i==row-1)
{
//cout<<233<<endl;
for(int p=0;p<column;p++)
{
if(board[i][p]=='O')
{
ans.push(make_pair(i,p));
unchanged[i][p]=1;
}
//cout<<i<<p<<endl;
}
}
else
{
if(board[i][0]=='O')
{
ans.push(make_pair(i,0));
unchanged[i][0]=1;
}
if(board[i][column-1]=='O')
{
ans.push(make_pair(i,column-1));
unchanged[i][column-1]=1;
}
}
}
while(!ans.empty())
{
pair<int,int> temp=ans.front();
ans.pop();
//unchanged[temp.first][temp.second]=1;
for(int i=0;i<4;i++)
{
if(temp.first+move_x[i]>=0&&temp.first+move_x[i]<row&&temp.second+move_y[i]>=0&&temp.second+move_y[i]<column)
{
if(board[temp.first+move_x[i]][temp.second+move_y[i]]=='O'&&unchanged[temp.first+move_x[i]][temp.second+move_y[i]]==0)
{
ans.push(make_pair(temp.first+move_x[i],temp.second+move_y[i]));
unchanged[temp.first+move_x[i]][temp.second+move_y[i]]=1;
//cout<<temp.first+move_x[i]<<temp.second+move_y[i]<<endl;
}
}
}
}
for(int i=0;i<row;i++)
{
for(int p=0;p<column;p++)
{
if(unchanged[i][p]==0)
board[i][p]='X';
}
}
}
};
总结:1.在复杂情况判断时一定要思考周全,逻辑严密。2.条件改变修改变量值时一定要对应(立马修改),否则会引起不可预知的错误。