LeetCode -1319 连通网络的操作次数

LeetCode -1319 连通网络的操作次数
LeetCode -1319 连通网络的操作次数
LeetCode -1319 连通网络的操作次数

class Solution {
    public int makeConnected(int n, int[][] connections) {
         int len = connections.length;
         if(len < n-1)
            return -1;
         UnionFind uf = new UnionFind(n);
         for(int i=0;i<len;i++){
             int[] connection = connections[i];
             uf.Union(connection[0],connection[1]);
         }
         return uf.count -1;
    }
    public class UnionFind{
        int[] parent;
        int count;
        public int getCount(){
            return count;
        }
        public UnionFind(int n){
            parent = new int[n];
            count = n;
            for(int i =0;i<n;i++){
                parent[i] = i;
            }
        }
        public int find(int x){
            if(parent[x] != x)
               parent[x] = find(parent[x]);
            return parent[x];
        }
        public boolean Union(int x,int y){
            int rootX = find(x);
            int rootY = find(y);
            if(rootX == rootY)
                return false ;
            parent[rootX] = rootY;
            count -= 1;
            return true; 
        }
    }
}
上一篇:95-24-020-Future-Future简介


下一篇:Java之多重循环控制基本使用