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 .
给定一个包含“X”和“O”的2D板,捕获所有被“X”包围的区域。捕获的意思就是说通过把被包围的区域中 'O' 替换成 'X' 来实现的。
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"不替换
public class Solution {
public void solve(char[][] board) {
if (board.length <= 0)
return;
int row = board.length;
int col = board[0].length;
for (int i = 0; i != row; i++) {
DFS(board, i, col - 1);
DFS(board, i, 0);
}
for (int i = 0; i != col; i++) {
DFS(board, 0, i);
DFS(board, row - 1, i);
}
for (int i = 0; i != row; i++)
for (int j = 0; j != col; j++) {
if (board[i][j] == 'O')
board[i][j] = 'X';
if (board[i][j] == '*')
board[i][j] = 'O';
}
}
public void DFS(char[][] board, int row, int col) {
if (row < 0 || row > (board.length - 1) || col < 0 || col > (board[0].length - 1))
return;
if (board[row][col] == 'O') {
board[row][col] = '*';
DFS(board, row - 1, col);
DFS(board, row + 1, col);
DFS(board, row, col - 1);
DFS(board, row, col + 1);
}
}
}