• + 0 comments

    Python solution based on : * Adjancency List * Breadth First Search * Combination for pairing with each other ungrouped

    def journeyToMoon(n, astronaut):

    matrix = [ [] for _ in range(n) ] 
    
    Vertex = set()
    
    for a in astronaut:
        _a , _b = a
        matrix[ _a ].append(_b)
        matrix[ _b ].append(_a)
    
        Vertex.add(_a)
        Vertex.add(_b)
    
    
    rank = 0
    
    visited = [ False ] * n
    
    print(Vertex)
    
    _G = []
    
    for i in Vertex:
    
        if not visited[i]:
            G = []
            q = [ i ]
            while q:
    
                curr = q[0]
                q = q[1:]
    
                G.append(curr)
    
                visited[curr] = True
    
                for x in matrix[curr]:
                    if not visited[x]:
                        visited[x] = True
                        q.append(x)
    
            _G.append(G)
    
    # unorganize
    n -= sum([ len(g) for g in _G ])
    
    print(f"re {n}")
    
    
    # print(" --> ",_G)
    
    result = 0
    
    for i in range(len(_G)):
        _ii = len(_G[i])
    
        for j in range(i + 1 ,len(_G)):
            result += _ii * len(_G[j])
    
        result += _ii * n
    
    return result + (( n * (n-1) ) // 2)