547. 朋友圈 Friend Circles

题目 <https://leetcode-cn.com/problems/friend-circles/>  

并查集=并(合并树)+查(查是否有公共父节点)

https://blog.csdn.net/Guo15331092/article/details/78702686

int findCircleNum(int** M, int MSize, int* MColSize){
    int *N = malloc(sizeof(int) * MSize),i,j,rooti,rootj;
    for(i=0;i<MSize;i++){
        N[i] = i;
    }
    
    for(i=0;i<MSize;i++){
        rooti = i;
        while(rooti != N[rooti]) rooti = N[rooti];
        for(j=i+1;j<MColSize[i];j++){
            if(M[i][j] == 1){
                rootj = j;
                while(rootj != N[rootj]) rootj = N[rootj];
                N[rootj] = rooti; 
            }
        }
    }

    int count = 0;
    for(i=0;i<MSize;i++){
        if(N[i] == i){
            count++;
        }
    }
    free(N);
    return count;
}

猜你喜欢

转载自blog.csdn.net/ZRXSLYG/article/details/111602740