Skip to content

Instantly share code, notes, and snippets.

@junjiah
Last active September 10, 2015 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junjiah/d4cd1936efb34943a964 to your computer and use it in GitHub Desktop.
Save junjiah/d4cd1936efb34943a964 to your computer and use it in GitHub Desktop.
solved 'Journey to the Moon' on hackerrank https://www.hackerrank.com/challenges/journey-to-the-moon
def get_connected_component_sizes(graph, node_num):
"""graph: Adjacency list for the graph.
node_num: Number of nodes."""
visited = [False] * node_num
component_sizes = []
for v in xrange(node_num):
if not visited[v]:
# DFS using stack.
stack, sz = [v], 0
visited[v] = True
while stack:
top_node = stack.pop()
sz += 1
for neighbor in graph[top_node]:
if not visited[neighbor]:
stack.append(neighbor)
visited[neighbor] = True
component_sizes.append(sz)
return component_sizes
if __name__ == '__main__':
node_num, edge_num = map(int,raw_input().split())
adjacency_list = [list() for _ in xrange(node_num)]
for _ in xrange(edge_num):
src, dest = map(int, raw_input().split())
# Note this is an undirected graph.
adjacency_list[src].append(dest)
adjacency_list[dest].append(src)
component_sizes = get_connected_component_sizes(
adjacency_list, node_num)
pair_num = 0
for sz in component_sizes:
pair_num += sz * (node_num - sz)
# Note each component has been calculated twice.
print pair_num / 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment