2
public int makeConnected(int n, int[][] connections) {3
int m = connections.length;4
if (m < n - 1) return -1;5
UnionFind uf = new UnionFind(n);7
for (int[] connection : connections) {8
uf.union(connection[0], connection[1]);10
return uf.getIsolated();19
public UnionFind(int n) {22
for (int i = 0; i < n; i++) {29
public int find(int x) {30
if (root[x] != x) root[x] = find(root[x]);34
public void union(int x, int y) {37
if (rootx == rooty) return;38
if (rank[rootx] > rank[rooty]) {40
} else if (rank[rootx] < rank[rooty]) {48
public int getIsolated() {49
for (int i = 0; i < root.length; i++) {50
if (root[i] == i) isolated++;