-
Notifications
You must be signed in to change notification settings - Fork 16
/
NumberOfProvinces.java
71 lines (62 loc) · 1.88 KB
/
NumberOfProvinces.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// https://leetcode.com/problems/number-of-provinces
// T: O(N^2)
// S: O(N)
public class NumberOfProvinces {
private static final class DisjointSet {
private final int[] array, rank;
public DisjointSet(int size) {
this.array = new int[size];
this.rank = new int[size];
for (int i = 0 ; i < size ; i++) {
array[i] = i;
rank[i] = 1;
}
}
// T: O(1)
public int find(int x) {
if (x == array[x]) {
return x;
}
final int rank = find(array[x]);
array[x] = rank;
return rank;
}
// T: O(1)
public boolean areConnected(int x, int y) {
return find(x) == find(y);
}
// T: O(1)
public void union(int x, int y) {
final int rootX = find(x), rootY = find(y);
if (rootX == rootY) {
return;
}
if (array[rootX] > array[rootY]) {
array[rootY] = rootX;
} else if (array[rootX] < array[rootY]) {
array[rootX] = rootY;
} else {
array[rootY] = rootX;
rank[rootX]++;
}
}
private int size() {
return array.length;
}
}
// T: O(n^2)
public int findCircleNum(int[][] isConnected) {
final int cities = isConnected.length;
final DisjointSet disjointSet = new DisjointSet(cities);
int provinces = cities;
for (int i = 0 ; i < cities ; i++) {
for (int j = i + 1 ; j < cities ; j++) {
if (isConnected[i][j] == 1 && disjointSet.find(i) != disjointSet.find(j)) {
disjointSet.union(i, j);
provinces--;
}
}
}
return provinces;
}
}