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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| class Solution { public void solve(char[][] board) { int n1 = board.length; if (n1 == 0) { return; } int n2 = board[0].length;
int[] parent = new int[n1 * n2]; for (int i = 0; i < parent.length; i++) { parent[i] = i; }
for (int i = 0; i < n1-1; i++) { for (int j = 1; j < n2; j++) { if (board[i][j] == 'O' && board[i][j - 1] == board[i][j]) { union(i * n2 + j, i * n2 + j - 1, parent); } if (board[i][j] == 'O' && board[i+1][j] == board[i][j]) { union(i * n2 + j, (i+1) * n2 + j, parent); } } }
List<Integer> list = new ArrayList<>(); for (int i = 0; i < parent.length; i++) { int x = i / n2; int y = i - x * n2; if (i == parent[i] && board[x][y] == 'O') { list.add(i); } }
for (int i = 0; i < list.size(); i++) { boolean b = true; for (int j = 0; j < parent.length; j++) { int x = j / n2; int y = j - x * n2; if (find(j, parent) == list.get(i) && (x == 0 || x == n1 - 1 || y == 0 || y == n2 - 1)) { b = false; } }
if (b) { for (int j = 0; j < parent.length; j++) { int x = j / n2; int y = j - x * n2; if (find(j, parent) == list.get(i)) { board[x][y] ='X'; } } } }
}
public int find(int k, int[] parent) { if (parent[k] != k) { parent[k] = find(parent[k], parent); } return parent[k]; }
public void union(int i, int j, int[] parent) { int x = find(i, parent); int y = find(j, parent); if (x != y) { parent[x] = y; } } }
|