leetcode 130. surrounded regions

130. Surrounded Regions

Difficulty: Medium

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:

1
2
3
4
X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:

1
2
3
4
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

Language: Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class  {
public void solve(char[][] board) {
if (board == null || board.length == 0 || board[0].length == 0) {
return;
}
markFromBorder(board);
flip(board);
}

private void markFromBorder(char[][] board) {
for (int i = 0; i < board.length; i++) {
dfsMark(board, i, 0);
dfsMark(board, i, board[0].length - 1);
}
for (int i = 1; i < board[0].length - 1; i++) {
dfsMark(board, 0, i);
dfsMark(board, board.length - 1, i);
}
}

int[] dx = {-1, 0, 1, 0};
int[] dy = {0, -1, 0, 1};

private void dfsMark(char[][] board, int i, int j) {
if (board[i][j] == 'X' || board[i][j] == 'Y') {
return;
}
if (board[i][j] == 'O') {
board[i][j] = 'Y';
}
for (int k = 0; k < 4; k++) {
int newX = i + dx[k];
int newY = j + dy[k];
if (newX >= 0 && newX < board.length && newY >= 0 && newY < board[0].length && board[newX][newY] == 'O') {
dfsMark(board, newX, newY);
}
}
}

private void flip(char[][] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
} else if (board[i][j] == 'Y') {
board[i][j] = 'O';
}
}
}
}
}