BFS array, which will enclose the area ' O ' for ' X '

Source: Internet
Author: User

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 '

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.