Given a 2D board containing ' x ' and ' O ', capture all regions surrounded by ' x '.
A region was captured by flipping all ' O ' s into the ' X ' s in this surrounded region.
For example,
x x x xx o o xx x o xx o x x
After running your function, the board should is:
x x x xx x x xx x x xx O x x
Idea: The enclosing zone's ' o ' becomes @ using the BFs method traversal, also using the array coordinate compression
Class Solution {
Public:
int max (int a, int b)
{
Return a > B a:b;
}
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0,-1}};
void BFs (vector<vector<char>>&board, int m, int n, int i, int j, int code)
{
Queue<int> Q
Q.push (I*code + j);
while (!q.empty ())
{
int tmp = Q.front ();
Q.pop ();
int row = Tmp/code;
int col = Tmp%code;
for (int k = 0; k < 4; k++)
{
if (row + dir[k][0] < m && row + dir[k][0] >= 0 && Col + dir[k][1] < n&& col + dir[k][1] >= 0)
{
if (Board[row + Dir[k][0]][col + dir[k][1]] = = ' O ') br> {
Board[row + Dir[k][0]][col + dir[k][1]] = ' @ ';
Q.push (row + dir[k][0]) * code + COL + dir[k][1]);
}
}
}
}
}
void Solve (Vector<vector<char>>&board)
{
int m = Board.size ();
int n = board[0].size ();
if (M < 3 | | n < 3)
Return
int code = MAX (M, n);
for (int i = 0; i < m; i++)
{
for (int j = 0; J < N; j + +)
{
if (board[i][j] = = ' O ' && (i = = 0 | | i = = M-1 | | j = = 0 | | j = n-1))
{
BOARD[I][J] = ' @ ';
BFS (board, M, N, I, J, code);
}
}
}
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] = = ' @ ')
BOARD[I][J] = ' O ';
}
}
}
};
BFS array, which will enclose the area ' O ' for ' X '