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都变成X,但不同的是边缘的O不算被包围,跟之前那道Number of Islands 岛屿的数量很类似,都可以用DFS来解。刚开始我的思路是DFS遍历中间的O,如果没有到达边缘,都变成X,如果到达了边缘,将之前变成X的再变回来。但是这样做非常的不方便,在网上看到大家普遍的做法是扫面矩阵的四条边,如果有O,则用DFS遍历,将所有连着的O都变成另一个字符,比如,这样剩下的O都是被包围的,然后将这些O变成X,把,这样剩下的O都是被包围的,然后将这些O变成X,把变回O就行了。代码如下:
1 class Solution { 2 public: 3 void solve(vector<vector<char>>& board) { 4 if (board.empty() || board[0].empty()) return; 5 int m = board.size(), n = board[0].size(); 6 for (int i = 0; i < m; ++i) { 7 for (int j = 0; j < n; ++j) { 8 if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { 9 if (board[i][j] == 'O') dfs(board, i , j); 10 } 11 } 12 } 13 for (int i = 0; i < m; ++i) { 14 for (int j = 0; j < n; ++j) { 15 if (board[i][j] == 'O') board[i][j] = 'X'; 16 if (board[i][j] == '$') board[i][j] = 'O'; 17 } 18 } 19 } 20 void dfs(vector<vector<char>> &board, int x, int y) { 21 int m = board.size(), n = board[0].size(); 22 vector<vector<int>> dir{{0,-1},{-1,0},{0,1},{1,0}}; 23 board[x][y] = '$'; 24 for (int i = 0; i < dir.size(); ++i) { 25 int dx = x + dir[i][0], dy = y + dir[i][1]; 26 if (dx >= 0 && dx < m && dy > 0 && dy < n && board[dx][dy] == 'O') { 27 dfs(board, dx, dy); 28 } 29 } 30 } 31 };