-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
72 lines (61 loc) · 1.61 KB
/
Copy pathsolution.java
File metadata and controls
72 lines (61 loc) · 1.61 KB
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
import java.util.*;
class DSU {
int[] parent;
int[] rank;
DSU(int n) {
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]); // path compression
}
return parent[x];
}
void unite(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return;
if (rank[a] < rank[b]) {
parent[a] = b;
} else if (rank[b] < rank[a]) {
parent[b] = a;
} else {
parent[b] = a;
rank[a]++;
}
}
}
class Solution {
int maxRemove(int[][] stones) {
int n = stones.length;
DSU dsu = new DSU(n);
HashMap<Integer, Integer> rowRep = new HashMap<>();
HashMap<Integer, Integer> colRep = new HashMap<>();
for (int i = 0; i < n; i++) {
int r = stones[i][0];
int c = stones[i][1];
if (rowRep.containsKey(r)) {
dsu.unite(i, rowRep.get(r));
} else {
rowRep.put(r, i);
}
if (colRep.containsKey(c)) {
dsu.unite(i, colRep.get(c));
} else {
colRep.put(c, i);
}
}
int components = 0;
for (int i = 0; i < n; i++) {
if (dsu.find(i) == i)
components++;
}
return n - components;
}
};