1319. The number of operations to connect to the network (and search set)

LeetCode: 1319. Number of operations connected to the network

Insert picture description here


And check the collection, the meaning of the topic is quite obvious.


Connect all computers of the same connected component. The rest is the number of computers that are not connected, and the number of connection cables required at the end is the number of isolated computers-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;
    }
}



Guess you like

Origin blog.csdn.net/qq_43765535/article/details/113037718