# [leetcode] 130.Surrounded Regions

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

class Solution {
public:
void solve(vector<vector<char>>& board) {
int row = board.size();
if(row == 0)return;
int col = board[0].size();
if(col == 0)return;
queue<pair<int,int>> OIndex;
for(auto i = 0; i < col; i++) {
if(board[0][i] == 'O') {
OIndex.push(make_pair(0, i));
board[0][i] = '+';
}
if(board[row - 1][i] == 'O') {
OIndex.push(make_pair(row-1, i));
board[row - 1][i] = '+';
}
}

for(auto i = 0; i < row; i++) {
if(board[i][0] == 'O') {
OIndex.push(make_pair(i, 0));
board[i][0] = '+';
}
if(board[i][col - 1] == 'O') {
OIndex.push(make_pair(i, col - 1));
board[i][col - 1] = '+';
}
}

while(!OIndex.empty()) {
pair<int,int> index = OIndex.front();
OIndex.pop();
if(index.first != 0 && board[index.first - 1][index.second] == 'O') {
board[index.first - 1][index.second] = '+';
OIndex.push(make_pair(index.first - 1, index.second));
}
if(index.first != row - 1 && board[index.first + 1][index.second] == 'O') {
board[index.first + 1][index.second] = '+';
OIndex.push(make_pair(index.first + 1, index.second));
}
if(index.second != 0 && board[index.first][index.second - 1] == 'O') {
board[index.first][index.second - 1] = '+';
OIndex.push(make_pair(index.first, index.second - 1));
}
if(index.second != col - 1 && board[index.first][index.second + 1] == 'O') {
board[index.first][index.second + 1] = '+';
OIndex.push(make_pair(index.first, index.second + 1));
}
}
for(auto i = 0; i < row; i++)
for(auto j = 0; j < col; j++){
if(board[i][j] == 'O')board[i][j] = 'X';
else if(board[i][j] == '+')board[i][j] = 'O';
}
}
};
• 本文已收录于以下专栏：

举报原因： 您举报文章：[leetcode] 130.Surrounded Regions 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)