title
Given a 2D board containing ‘X’ and ‘O’ (the letter O), capture all regions surrounded by ‘X’.
A region is captured by flipping all ‘O’s into ‘X’s in that surrounded region.
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
Explanation:
Surrounded regions shouldn’t be on the border, which means that any ‘O’ on the border of the board are not flipped to ‘X’. Any ‘O’ that is not on the border and it is not connected to an ‘O’ on the border will be flipped to ‘X’. Two cells are connected if they are adjacent cells connected horizontally or vertically.
solution
使被 ‘X’ 包围的 ‘O’ 转换为 ‘X’。
先填充最外侧,剩下的就是里侧了。
class Solution {
public:
void dfs(vector<vector<char>> &board, int r, int c) {
if (r < 0 || r >= board.size() || c < 0 || c >= board[0].size() || board[r][c] != 'O')
return;
board[r][c] = 'T';
dfs(board, r + 1, c);
dfs(board, r - 1, c);
dfs(board, r, c + 1);
dfs(board,r, c - 1);
}
void solve(vector<vector<char>>& board) {
if (board.size() == 0)
return;
for (int i = 0; i < board.size(); i++) {
dfs(board, i, 0);
dfs(board, i, board[0].size() - 1);
}
for (int i = 0; i < board[0].size(); i++) {
dfs(board, 0, i);
dfs(board, board.size() - 1, i);
}
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[0].size(); j++) {
if (board[i][j] == 'T') {
board[i][j] = 'O';
}
else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
};