Simple solution


  • 0

    took visited array, which keeps track of all visited nodes
    will iterate over these unvisited nodes, answer will be how many times it goes inside this if loop.
    For example take node 0, Since node 0 is unvisited it will go inside if loop and check whether it is connected to other nodes,. suppose, lets take input 4 [[0,1],[2.0],[1,3]]

    In this scenario, first node 0 will call node 1, in recursive call then node 1 will get visited and it will call node 3. node 3 will become visited and it won't call any node because it not connected to other node, Then node 2 will get call at the end and it will get visited. Now since all nodes are visited it should return;

    public int countComponents(int n, int[][] edges) {
    int count=0;

       boolean b[] = new boolean[n];  
       
       for(int i=0; i<n; i++){   
    
    
    
           if(!b[i]){
               count++;
               helper(i,edges,b);
           }
       }
       
       return count;
        
    }
    
    
    public void helper (int i,int a[][], boolean b[]){
        
        if(!b[i]){
            b[i]=true;
       
        }
        else
        return;
    
     for(int k=0; k<a.length; k++){
        {
            if(a[k][0]==i)
        helper(a[k][1],a,b);
        
           if(a[k][1]==i)
            helper(a[k][0],a,b); 
        }
        
        
    }
    }

Log in to reply
 

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