CPP Union Find Method


  • 0
    D
    int findCircleNum(vector<vector<int>>& M) {
        if (!M.size()) return 0;
        
        vector<int> root(M.size());
        for (int i = 0; i < root.size(); ++i) root[i] = i;
        
        for (int i = 0; i < M.size(); ++i) for (int j = i+1; j < M.size(); ++j) {
            if (M[i][j]) {
                root[findRoot(i, root)] = root[findRoot(j, root)];
            }
        }
        
        unordered_set<int> st;
        for (int i = 0; i < root.size(); ++i) st.insert(findRoot(i, root));
        
        return st.size();
    }
    
    // Implement find root method
    int findRoot(int i, vector<int>& root) {
        while (root[i] != i) i = root[i];
        return i;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.