标签:
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
思路:将包围区域的‘o‘变成@ 采用BFS方法遍历,还使用了数组坐标压缩
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‘)
{
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‘;
}
}
}
};
标签:
原文地址:http://www.cnblogs.com/ranranblog/p/5625789.html