Sharing my 256ms C++ solution


  • 0
    T
    class Solution {
    private:
        void countComponentsHelper(int n, vector<vector<int>>& myGraph, vector<bool>& visited)
        {
            if(visited[n])
                return;
            else
            {
                visited[n] = true;
                vector<int> v = myGraph[n];
                for(int i=0; i<v.size(); i++)
                    countComponentsHelper(v[i], myGraph, visited);
            }
        }
        
    public:
        int countComponents(int n, vector<pair<int, int>>& edges) {
            vector<vector<int>> myGraph(n, vector<int>(0));
            vector<bool> visited(n, false);
            
            int N = edges.size(), i, first, second;
            for(i=0; i<N; i++)
            {
                first = edges[i].first;
                second = edges[i].second;
                myGraph[first].push_back(second);
                myGraph[second].push_back(first);
            }
            
            int count = 0;
            for(i=0; i<n; i++)
            {
                if(visited[i]==false)
                {
                    countComponentsHelper(i, myGraph, visited);
                    count++;
                }
            }
            
            return count;
        }
    };

Log in to reply
 

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