C++ short easy to understand union find solution


  • 1
    J
    class Solution {
    public:
        int countComponents(int n, vector<pair<int, int>>& edges) {
            int count = 0;
            vector<int> root(n, -1);
            for(int i=0; i<n; i++)
            {
                root[i] = i;
            }
            
            for(auto edge : edges)
            {
                
                int f = edge.first;
                int s = edge.second;
                while(f != root[f])
                    f = root[f];
                while(s != root[s])
                    s = root[s];
                
                root[f] = s;
            }
            for(int i=0; i<n; i++)
            {
                if(root[i] == i)
                    ++count;
            }
            return count;
        }
    };
    

Log in to reply
 

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