130. Surrounded Regions
Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
Explanation: Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.public void solve(char[][] board) {
int m = board.length, n = board[0].length;
// 对每一行,遍历在column左右边界上的‘O’
for (int i = 0; i < m; i++) {
if (board[i][0] == 'O') dfs(board, i, 0);
if (board[i][n - 1] == 'O') dfs(board, i, n - 1);
}
// 对每一列,遍历在row上下边界上的‘O’
for (int i = 0; i < n; i++) {
if (board[0][i] == 'O') dfs(board, 0, i);
if (board[m - 1][i] == 'O') dfs(board, m - 1, i);
}
// change 'O' to 'X' and restore 'A' to 'O'
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'O') board[i][j] = 'X';
else if (board[i][j] == 'A') board[i][j] = 'O';
}
}
}
private void dfs(char[][] board, int i, int j) {
int m = board.length, n = board[0].length;
// 注意这里是i>=m和j>=n,因为这两种情况是不允许的
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != 'O') return;
board[i][j] = 'A';
dfs(board, i + 1, j);
dfs(board, i - 1, j);
dfs(board, i, j + 1);
dfs(board, i, j - 1);
}Last updated
