# LeetCode | 130. Surrounded Regions

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.

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


Explanation:

Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

class Solution {
public:
void solve(vector<vector<char>>& board) {
if(board.size() < 1)
return;
int h = board.size();
int w = board.size();
if(w < 1)
return;

vector<vector<int>> record(h, vector<int>(w, 0));
vector<vector<int>> mboard(h, vector<int>(w, 0));

queue<pair<int, int>> q;
for(int i = 0; i<h; i++)
{
for(int j = 0; j<w; j++)
{
if(i == 0 || i == h - 1 || j == 0 || j == w - 1)
{
if(board[i][j] == 'O' && !record[i][j])
{
q.push(pair<int, int>(i, j));
mboard[i][j] = 1;
}
record[i][j] = 1;
}
}
}

vector<vector<int>> d = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while(!q.empty())
{
pair<int, int> cur = q.front();
q.pop();
pair<int, int> pos;
for(int k = 0; k < 4; k++)
{
pos.first = cur.first + d[k];
pos.second = cur.second + d[k];
if(pos.first < 0 || pos.first >= h || pos.second < 0 || pos.second >= w)
continue;

if(board[pos.first][pos.second] == 'O' && !record[pos.first][pos.second])
{
mboard[pos.first][pos.second] = 1;
q.push(pos);
}

record[pos.first][pos.second] = 1;
}
}

for(int i = 0; i<h; i++)
{
for(int j = 0; j<w; j++)
{
if(mboard[i][j] == 1)
continue;
board[i][j] = 'X';
}
}
return;
}
};



Anyway, hope for the best.

02-06 56
12-13 539 04-29 690
12-16 47
08-15 1559
08-12 1224
01-24 160
10-14 95
01-30 266
04-17 1523