My simple c++ solution similar to all my graph-related problem solution


  • 2
    K
    class Solution {
    public:
    int countComponents(int n, vector<pair<int, int>>& edges) {
        if(edges.size()==0)return n;
        vector<int>nums[n];
        vector<bool>visited(n, false);
        int count=0;
        for(auto & e : edges){
            nums[e.first].push_back(e.second);
            nums[e.second].push_back(e.first);
        }
        
        for(int i=0; i < n; i++){
            if(!visited[i]){
                count++;
                helper(i, nums, visited);
            }
        }
        return count;
    }
    void helper(int v, vector<int>nums[], vector<bool> & visited){
        if(visited[v])return;
        visited[v]=true;
        for(auto & node : nums[v]){
            helper(node, nums, visited);
        }
    }
    };

Log in to reply
 

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