标签:
X X X X
X O O X
X X O X
X O X X
变成
X X X X
X X X X
X X X X
X O X X
思路:有点像围棋里一块区域是否有气,只有有气的才能存活下来。即只有‘O’到达了四条边界才可以存活,因此从四条边界开始做广搜,将所有搜索到的‘O‘赋值为‘1’,然后遍历整个矩阵将所有之前没有被赋值的‘O’赋值为‘X’,将‘1’还原为‘O’即可。
class Solution {
public:
void solve(vector<vector<char>> &board) {
if (board.empty())
return;
int width = board[0].size();
int height = board.size();
for (size_t i = 0; i < width; i++)
{
if (board[0][i] == ‘O‘)
bfs(0, i, board);
if (board[height - 1][i] == ‘O‘)
bfs(height-1, i, board);
}
for (size_t i = 0; i < height; i++)
{
if (board[i][0] == ‘O‘)
bfs(i, 0, board);
if (board[i][width - 1] == ‘O‘)
bfs(i, width - 1, board);
}
for (size_t i = 0; i < height; i++)
{
for (size_t j = 0; j < width; j++)
{
if (board[i][j] == ‘1‘)
board[i][j] = ‘O‘;
else if (board[i][j] == ‘O‘)
{
board[i][j] = ‘X‘;
}
}
}
}
void bfs(int x,int y, vector<vector<char> >&board)
{
board[x][y] = ‘1‘;
queue<Point> qPoint;
qPoint.push(Point(x,y));
Point tmpPoint=Point(0,0);
int xBound = board.size();
int yBound = board[0].size();
while (!qPoint.empty())
{
tmpPoint = qPoint.front();
x = tmpPoint.x;
y = tmpPoint.y;
if (isInside(x+1, y, xBound, yBound) && board[x+1][y] == ‘O‘)
{
qPoint.push(Point(x+1, y));
board[x+1][y] = ‘1‘;
}
if (isInside(x-1, y, xBound, yBound) && board[x-1][y] == ‘O‘)
{
qPoint.push(Point(x-1, y));
board[x-1][y] = ‘1‘;
}
if (isInside(x, y+1, xBound, yBound) && board[x][y+1] == ‘O‘)
{
qPoint.push(Point(x, y+1));
board[x][y+1] = ‘1‘;
}
if (isInside(x, y - 1, xBound, yBound) && board[x][y - 1] == ‘O‘)
{
qPoint.push(Point(x, y - 1));
board[x][y - 1] = ‘1‘;
}
qPoint.pop();
}
}
bool isInside(int x, int y, int xBound, int yBound)
{
return x >= 0 && x < xBound && y >= 0 && y < yBound;
}
struct Point
{
int x;
int y;
Point(int a, int b) :x(a), y(b){}
};
};
标签:
原文地址:http://www.cnblogs.com/flyjameschen/p/fcdadc64b3ea86ad9861337babbd17ec.html