• + 0 comments
    class Result {
        
        static int[] parent;
        
        
       public static void union(int a, int b){
            int fa = find(a);
            int fb = find(b);
            
            if(fa != fb){
                if(fa > fb){
                    parent[fa] = fb;
                }else{
                    parent[fb] = fa;
                }
            }
        }
        public static int find(int a){
            if(parent[a] == a) return a;
            else return parent[a] = find(parent[a]);
        }
    
        public static long journeyToMoon(int n, List<List<Integer>> astronaut) {
    
            parent = new int[n];
            for(int i=0; i<n; i++){
                parent[i] = i;
            }
            
            for(int i=0;i<astronaut.size();i++){
                union(astronaut.get(i).get(0), astronaut.get(i).get(1));
            }
            
    
            long count = 0;
            for(int i=0;i<n;i++){
                for(int j=i+1;j<n;j++){
                    int one = find(i);
                    int two = find(j);
                    if(one!=two){
                        count++;
                    }
                }
            }
            
            return count;
            
        }
    
    }