We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Journey to the Moon
You are viewing a single comment's thread. Return to all comments →
Python solution based on : * Adjancency List * Breadth First Search * Combination for pairing with each other ungrouped
def journeyToMoon(n, astronaut):