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’标记成‘X’并且恢复外围的‘.’为‘O’。注意DFS时最外面的一圈已经在最开始处理过了,所以DFS时无需再进入了,否则会报内存错误。
DFS:
1 class Solution { 2 public: 3 void dfs(vector<vector<char>> &board, int x, int y) { 4 board[x][y] = '#'; 5 const int dx[4] = {0, 1, 0, -1}; 6 const int dy[4] = {1, 0, -1, 0}; 7 for (int i = 0; i < 4; ++i) { 8 int xx = x + dx[i], yy = y + dy[i]; 9 if (xx > 0 && xx < board.size() - 1 && yy > 0 && yy < board[0].size() - 1 && board[xx][yy] == 'O') 10 dfs(board, xx, yy); 11 } 12 } 13 void solve(vector<vector<char>>& board) { 14 if (board.empty() || board[0].empty()) return; 15 int N = board.size(), M = board[0].size(); 16 for (int i = 0; i < N; ++i) { 17 if (board[i][0] == 'O') dfs(board, i, 0); 18 if (board[i][M-1] == 'O') dfs(board, i, M-1); 19 } 20 for (int j = 0; j < M; ++j) { 21 if (board[0][j] == 'O') dfs(board, 0, j); 22 if (board[N-1][j] == 'O') dfs(board, N-1, j); 23 } 24 for (int i = 0; i < N; ++i) { 25 for (int j = 0; j < M; ++j) { 26 if (board[i][j] == '#') board[i][j] = 'O'; 27 else if (board[i][j] == 'O') board[i][j] = 'X'; 28 } 29 } 30 return; 31 } 32 };
BFS:
1 class Solution { 2 public: 3 void solve(vector<vector<char>>& board) { 4 if (board.empty() || board[0].empty()) return; 5 int N = board.size(), M = board[0].size(); 6 queue<pair<int, int>> que; 7 for (int i = 0; i < N; ++i) { 8 if (board[i][0] == 'O') que.push({i, 0}); 9 if (board[i][M-1] == 'O') que.push({i, M-1}); 10 } 11 for (int j = 0; j < M; ++j) { 12 if (board[0][j] == 'O') que.push({0, j}); 13 if (board[N-1][j] == 'O') que.push({N-1, j}); 14 } 15 const int dx[4] = {0, 1, 0, -1}; 16 const int dy[4] = {1, 0, -1, 0}; 17 for (; !que.empty(); que.pop()) { 18 auto u = que.front(); 19 int x = u.first, y = u.second; 20 board[x][y] = '#'; 21 for (int i = 0; i < 4; ++i) { 22 int xx = x + dx[i], yy = y + dy[i]; 23 if (xx >= 0 && xx < N && yy >= 0 && yy < M && board[xx][yy] == 'O') que.push({xx, yy}); 24 } 25 } 26 for (int i = 0; i < N; ++i) { 27 for (int j = 0; j < M; ++j) { 28 if (board[i][j] == '#') board[i][j] = 'O'; 29 else if (board[i][j] == 'O') board[i][j] = 'X'; 30 } 31 } 32 return; 33 } 34 };