-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.java
41 lines (39 loc) · 1.25 KB
/
Solution.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
class Solution {
private int[] p;
private int[][] dirs = new int[][]{{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
public void solve(char[][] board) {
int m = board.length, n = board[0].length;
p = new int[m * n + 1];
for (int i = 0; i < p.length; ++i) {
p[i] = i;
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == 'O') {
if (i == 0 || j == 0 || i == m - 1 || j == n - 1) {
p[find(i * n + j)] = find(m * n);
} else {
for (int[] e : dirs) {
if (board[i + e[0]][j + e[1]] == 'O') {
p[find(i * n + j)] = find((i + e[0]) * n + j + e[1]);
}
}
}
}
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == 'O' && find(i * n + j) != find(m * n)) {
board[i][j] = 'X';
}
}
}
}
private int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
}