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.
给出一个由‘O’和’X’组成的矩阵,要把被’X‘包围的’O’转换成‘X’。
但是边界上的‘O’和与边界的‘O’相连通的’O’不作转换
思路:
因为和边界‘O’连通的’O’不作转换,所以要找出边界‘O’的连通区域,并做标记,然后标记之外的’O’转为‘X’
连通区域还是和200题一样的dfs方法,标记成‘O’和‘X’之外的字符以防止重复搜索
注意不要忘了dfs下边界和右边界
public void solve(char[][] board) {
if(board == null || board.length == 0) {
return;
}
int rows = board.length;
int cols = board[0].length;
for(int i = 0; i < rows; i++) {
dfs(board, i, 0, rows, cols);
dfs(board, i, cols-1, rows, cols);
}
for(int j = 0; j < cols; j++) {
dfs(board, 0, j, rows, cols);
dfs(board, rows-1, j, rows, cols);
}
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(board[i][j] == 'O') {
board[i][j] = 'X';
} else if(board[i][j] == 'G') {
board[i][j] = 'O';
}
}
}
}
public void dfs(char[][] board, int i, int j, int rows, int cols) {
if(i < 0 || i >= rows || j < 0 || j >= cols || board[i][j] != 'O') {
return;
}
board[i][j] = 'G';
dfs(board, i-1, j, rows, cols); //up
dfs(board, i+1, j, rows, cols); //down
dfs(board, i, j-1, rows, cols); //left
dfs(board, i, j+1, rows, cols); //right
}