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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
| /**
[[3,2],[3,1],[4,4],[1,1],[0,2],[4,0]]
x x 4 x x
x 3 x x x
x x x x x
x 1 0 x x
5 x x x 2
[[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
0 1 x
2 x 3
x 4 5
0 r x
r x r
x r r
[[0,1],[1,0]]
* 0
1 *
[[3,2],[3,1],[4,4],[1,1],[0,2],[4,0]]
* * 4 * *
* 3 * * *
* * * * *
* 1 0 * *
5 * * * 2
**/
class Solution {
int n;
public int removeStones(int[][] stones) {
n = 0;
for (int i = 0; i < stones.length; i++) {
n = Math.max(n, stones[i][0]);
n = Math.max(n, stones[i][1]);
}
n = n + 1;
UF uf = new UF(n + n);
for (int[] stone: stones) {
uf.union(stone[0], n + stone[1]);
}
Map<Integer, Integer> counts = new HashMap();
for (int[] stone: stones) {
int id = uf.find(stone[0]);
int componentSize = counts.getOrDefault(id, 0);
counts.put(id, componentSize + 1);
}
Integer maxComponentSize = 0;
for (Map.Entry<Integer, Integer> keyValue: counts.entrySet()) {
if (keyValue.getValue() > 1) {
maxComponentSize += keyValue.getValue() - 1;
}
}
return maxComponentSize;
}
class UF {
private int n;
private int[] a;
private int[] sz;
public UF(int n) {
this.n = n;
this.a = new int[n];
this.sz = new int[n];
for (int i = 0; i < n; i++) {
a[i] = i;
sz[i] = 1;
}
}
void union(int p, int q) {
int pid = find(p);
int qid = find(q);
if (pid == qid) return;
if (sz[pid] >= sz[qid]) {
a[qid] = a[pid];
sz[pid] += sz[qid];
} else {
a[pid] = qid;
sz[qid] += sz[pid];
}
}
int find(int p) {
while(p != a[p]) {
p = a[p];
}
return p;
}
}
}
|