Description:
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.
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
Solutions:
//用BFS遍历
class Solution {
public:
void solve(vector<vector<char> > &board) {
int row = board.size();
if(row == 0){
return;
}
int col = board[0].size();
if(row <= 2 || col <= 2){
return;
}
for(int i = 0;i < col;++i){
BFS(board,row,col,0,i);
BFS(board,row,col,row-1,i);
}
for(int j = 0;j < row;++j){
BFS(board,row,col,j,0);
BFS(board,row,col,j,col-1);
}
for(int i = 0;i < row;++i){
for(int j = 0;j < col;j++){
if(board[i][j] == 'O'){
board[i][j] = 'X';
}
else if(board[i][j] == '.'){
board[i][j] = 'O';
}
}
}
}
private:
void BFS(vector<vector<char>> &board,int row,int col,int x,int y){
queue<pair<int,int> > q;
Pass(board,row,col,x,y,q);
while(!q.empty()){
pair<int,int> point = q.front();
q.pop();
x = point.first;
y = point.second;
Pass(board,row,col,x,y+1,q);
Pass(board,row,col,x,y-1,q);
Pass(board,row,col,x-1,y,q);
Pass(board,row,col,x+1,y,q);
}
}
void Pass(vector<vector<char>> &board,int row,int col,int x,int y,queue<pair<int,int> > &q){
if(x < 0 || x >= row || y < 0 || y >= col || board[x][y] != 'O'){
return;
}
board[x][y] = '.';
q.push(make_pair(x,y));
}
};
本文介绍了一种使用广度优先搜索(BFS)算法来捕获二维棋盘中被X包围的所有O型区域的方法。通过将边缘的O标记为保留状态,最后将所有未标记的O转换为X,实现区域捕获。该算法适用于编程竞赛和技术面试。
520

被折叠的 条评论
为什么被折叠?



