547.Friend Circles

class Solution {
public:
    int findCircleNum(vector<vector<int>>& M) {
        vector<int> root(M.size(),0);
        int ret = M.size();
        for(int i = 0; i< root.size(); ++i) {
            root[i]=i;
        }
        for(int m = 0; m < M.size(); ++m) {
            for(int n = 0; n < M.size(); ++n) {
                if (M[m][n] == 1) {
                    int f1 = find(root,m);
                    int f2 = find(root,n);
                    if(f1 != f2) {
                        ret--;
                        root[f2] = f1;
                    }
                }
            }
        }
        return ret;


    }
    int find(vector<int> root, int i) {
        while(i != root[i]) {
            root[i] = root[root[i]];
            i = root[i];
        }
        return i;
    }
};

results matching ""

    No results matching ""