您的位置:首页 > 其它

leetcode 130: Surrounded Regions

2015-08-17 00:48 253 查看
The algorithm is not so hard to think. Just try from the boarder, if there is an 'O', DFS or BFS and change all 'O's in that region to another character. After that, change all 'O's to 'X' and all different characters (I use 'n') to 'O'. The trick when using
BFS here is to change the character before push into the queue, or it will push some positions that are already in the queue and finally cause TLE.

class Solution {
public:
void solve(vector<vector<char>>& board) {
if(board.empty())
return;
int m=board.size();
int n=board[0].size();
for(int i=0;i<m;i++)
{
if(board[i][0]=='O')
bfs(board,i,0,m,n);
if(board[i][n-1]=='O')
bfs(board,i,n-1,m,n);
}
for(int i=0;i<n;i++)
{
if(board[0][i]=='O')
bfs(board,0,i,m,n);
if(board[m-1][i]=='O')
bfs(board,m-1,i,m,n);
}
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if(board[i][j]=='O')
board[i][j]='X';
else if(board[i][j]=='n')
board[i][j]='O';
}
}
void bfs(vector<vector<char> >& board,int r,int c,int m,int n)
{
queue<pair<int,int> > q;
board[r][c]='n';
q.push(make_pair(r,c));
while(!q.empty())
{
r=q.front().first;
c=q.front().second;
q.pop();
if(r>0&&board[r-1][c]=='O')
{
board[r-1][c]='n';
q.push(make_pair(r-1,c));
}
if(r<m-1&&board[r+1][c]=='O')
{
board[r+1][c]='n';
q.push(make_pair(r+1,c));
}
if(c>0&&board[r][c-1]=='O')
{
board[r][c-1]='n';
q.push(make_pair(r,c-1));
}
if(c<n-1&&board[r][c+1]=='O')
{
board[r][c+1]='n';
q.push(make_pair(r,c+1));
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: