1319. 连通网络的操作次数 ( 并查集 )

LeetCode:1319. 连通网络的操作次数

在这里插入图片描述


并查集, 题目意思还是比较明显的.


将同一个连通分量的所有计算机连通起来。 剩下的就是没有被连通的计算机数量, 最后需要的连接线缆数就是 孤立的计算机数量 - 1



AC Code

class Solution {
    
    

    int[] fa = new int[(int)1e5 + 7];

    public int findset(int x) {
    
    
        if(x == fa[x]) return x;
        return fa[x] = findset(fa[x]);
    }

    public void union(int x, int y) {
    
    
        int rootx = findset(x);
        int rooty = findset(y);
        if(rootx != rooty) fa[rootx] = rooty;
    }

    public int makeConnected(int n, int[][] c) {
    
    
        int need = c.length;
        
        // 数量不足
        if(n - 1 > need) return -1;

        // 初始化
        for(int i = 0; i < n; i++) fa[i] = i;

        // 连通
        for(int i = 0; i < need; i++) {
    
    
            int x = findset(c[i][0]);
            int y = findset(c[i][1]);
            if(x != y) {
    
    
                // 连通
                fa[x] = y;
            }
        }


        int cnt = 0;
        // 计算
        for(int i = 0; i < n; i++) {
    
    
            if(fa[i] == i) cnt++;
        }

        return cnt - 1;
    }
}



猜你喜欢

转载自blog.csdn.net/qq_43765535/article/details/113037718