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作为入口进行广度优先遍历或者DFS,遍历过的点都做标记,四周都做一遍,之后矩阵中为O并且没有被访问的元素变成X即可.
class Solution {
public:
int movx[4] = { 0, 0, 1, -1 };
int movy[4] = { 1, -1, 0, 0 };
struct position{
int x;
int y;
position(int x1, int y1) :x(x1), y(y1){};
};
void myfind(vector<vector<char>> &board, vector<vector<bool>>& visit, int x, int y)
{
visit[x][y] = 1;
int rows = board.size();
if (rows <= 2)
return;
int cols = board[0].size();
if (cols <= 2)
return;
queue<position> que;
position root(x, y);
que.push(root);
while (!que.empty())
{
position temp = que.front();
que.pop();
for (int i = 0; i<4; ++i)
{
int nx = temp.x + movx[i];
int ny = temp.y + movy[i];
if (nx >= 0 && nx<rows&&ny >= 0 && ny<cols&&visit[nx][ny] == 0 && board[nx][ny] == 'O')
{
que.push(position(nx, ny));
visit[nx][ny] = 1;
}
}
}
}
void solve(vector<vector<char>> &board) {
int rows = board.size();
if (rows <= 2)
return;
int cols = board[0].size();
if (cols <= 2)
return;
vector<vector<bool>> visit(rows, vector<bool>(cols, 0));
for (int i = 0; i<cols; ++i)
{
if (board[0][i] == 'O'&&visit[0][i] == 0)
{
myfind(board, visit, 0, i);
}
if (board[rows - 1][i] == 'O'&&visit[rows-1][i] == 0)
{
myfind(board, visit, rows - 1, i);
}
}
for (int i = 0; i<rows; ++i)
{
if (board[i][0] == 'O'&&visit[i][0] == 0)
{
myfind(board, visit, i, 0);
}
if (board[i][cols - 1] == 'O'&&visit[i][cols - 1] == 0)
{
myfind(board, visit, i, cols - 1);
}
}
for (int i = 0; i<rows; ++i)
{
for (int j = 0; j<cols; ++j){
if (board[i][j] == 'O'&&visit[i][j] == 0)
board[i][j] = 'X';
}
}
}
};