-
Notifications
You must be signed in to change notification settings - Fork 29
/
Solution130.java
52 lines (41 loc) · 1.14 KB
/
Solution130.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
52
package backstracking_problem;
/**
* floodfill 洪水填充算法——深度优先遍历
*/
public class Solution130 {
int[][] d = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int m , n;
public void solve(char[][] board) {
if (board == null || board.length == 0) {
return;
}
m = board.length;
n = board[0].length;
for (int i = 0; i < m; i++) {
dfs(board, i, 0);
dfs(board, i, n - 1);
}
for (int i = 0; i < n; i++) {
dfs(board, 0, i);
dfs(board, m - 1, i);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'T') {
board[i][j] = 'O';
} else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
private void dfs(char[][] board, int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != 'O') {
return;
}
board[i][j] = 'T';
for (int[] d : d) {
dfs(board, i + d[0], j + d[1]);
}
}
}