[LeetCode] Problem 130 - Surrounded Regions

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.

Code

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
public void solve(char[][] board) {
if (board == null || board.length == 0 || board[0].length == 0)
return;

int m = board.length;
int n = board[0].length;

for (int i = 0; i < n; i++) {
dfs(board, m, n, 0, i);
dfs(board, m, n, m - 1, i);
}

for (int i = 0; i < m; i++) {
dfs(board, m, n, i, 0);
dfs(board, m, n, i, n - 1);
}

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'O')
board[i][j] = 'X';

if (board[i][j] == 'T')
board[i][j] = 'O';
}
}
}

private void dfs(char[][] board, int m, int n, int x, int y) {
if (x < 0 || y < 0 || x >= m || y >= n)
return;

if (board[x][y] != 'O')
return;

board[x][y] = 'T';
dfs(board, m, n, x + 1, y);
dfs(board, m, n, x - 1, y);
dfs(board, m, n, x, y + 1);
dfs(board, m, n, x, y - 1);
}