-
Notifications
You must be signed in to change notification settings - Fork 0
/
130-SurroundedRegions.java
49 lines (40 loc) · 1.33 KB
/
130-SurroundedRegions.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
// 130. Surrounded Regions
class Solution {
int rows;
int cols;
public void solve(char[][] board) {
if (board == null || board.length == 0)
return;
rows = board.length;
cols = board[0].length;
for(int i = 0; i < rows; i++) {
if(board[i][0] == 'O')
dfs(board, i, 0);
if(board[i][cols-1] == 'O')
dfs(board, i, cols-1);
}
for(int j = 0; j < cols; j++) {
if(board[0][j] == 'O')
dfs(board, 0, j);
if(board[rows-1][j] == 'O')
dfs(board, rows-1, j);
}
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(board[i][j] == 'O')
board[i][j] = 'X';
if(board[i][j] == 'E')
board[i][j] = 'O';
}
}
}
private void dfs(char[][] board, int i, int j) {
if(i < 0 || i >= rows || j < 0 || j >= cols || board[i][j] != 'O')
return;
board[i][j] = 'E';
dfs(board, i-1, j);
dfs(board, i+1, j);
dfs(board, i, j-1);
dfs(board, i, j+1);
}
}