解法一:并查集
先判断线和结点数量的大小,线的数量小于结点数量-1则必然无法连通。
然后就是一个并查集问题,有 K 个独立的连通分支,就需要 K-1 次操作。
import java.util.*;class Solution {private int[] father;public int makeConnected(int n, int[][] connections) {int lineNum = connections.length;if (lineNum < n - 1) {return -1;}init(n);for (int[] pair : connections) {union(pair[0], pair[1]);}Set<Integer> set = new HashSet<>();for (int i : father) {set.add(find(i));}return set.size() - 1;}private void init(int n) {father = new int[n];for (int i = 0; i < n; ++i) {father[i] = i;}}private void union(int x, int y) {father[x] = find(x);father[y] = find(y);father[father[x]] = father[y];}private int find(int x) {return father[x] == x ? x : find(father[x]);}}
