Surrounded Regions
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' 的结点开始进行深搜,若是 'O', 则设置已访问为 true. 接着对其余所有非边界结点进行遍历,若是 'O' 且未访问,则将该结点重置为 'X' .
typedef pair<int, int> point; void dfs(point p, int r, int c, vector<vector<char> > &board, vector<vector<bool> > &visited) { visited[p.first][p.second] = true; int dx[] = {-1, 0, 1, 0}, dy[] = {0, -1, 0, 1}; for(int i = 0; i < 4; ++i) { int x = p.first + dx[i], y = p.second + dy[i]; if(0 < x && x < r && 0 < y && y < c && board[x][y] == 'O' && !visited[x][y]) dfs(point(x, y), r, c, board, visited); } } class Solution { public: void solve(vector<vector<char>> &board) { if(!board.size() || !board[0].size()) return; int row = board.size(), col = board[0].size(); vector<vector<bool>> visited(row, vector<bool>(col, false)); for(int j = 0; j < col; ++j) { if(board[0][j] == 'O' && !visited[0][j]) dfs(point(0, j), row, col, board, visited); if(board[row-1][j] == 'O' && !visited[row-1][j]) dfs(point(row-1, j), row, col, board, visited); } for(int i = 0; i < row; ++i) { if(board[i][0] == 'O' && !visited[i][0]) dfs(point(i, 0), row, col, board, visited); if(board[i][row-1] == 'O' && !visited[i][row-1]) dfs(point(i, col-1), row, col, board, visited); } for(int i = 1; i < row-1; ++i) for(int j = 1; j < col-1; ++j) if(board[i][j] == 'O' && !visited[i][j]) board[i][j] = 'X'; } };