Created
November 1, 2020 14:05
-
-
Save kendhia/d450a90a37561f6a2f5c817e7fa3e28d to your computer and use it in GitHub Desktop.
My solution for the roads and libraries graph problem. https://www.hackerrank.com/challenges/torque-and-development
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
def dfs(visited_dfs, graph_dfs, node, l_c): | |
# This is the usual dfs algorithm | |
# just we need to keep count of the length of our component (l_c) | |
if node not in visited_dfs: | |
l_c += 1 | |
visited_dfs.add(node) | |
for neighbour in graph_dfs[node]: | |
l_c = dfs(visited_dfs, graph_dfs, neighbour, l_c) | |
return l_c | |
# Complete the roadsAndLibraries function below. | |
def roadsAndLibraries(n, c_lib, c_road, a): | |
if c_road >= c_lib: | |
return n * c_lib | |
g = defaultdict(list) | |
nodes = set() | |
#convert the given matrix to a graph (adjacent list) | |
for pair in a: | |
g[pair[0]].append(pair[1]) | |
g[pair[1]].append(pair[0]) | |
nodes.add(pair[0]) | |
nodes.add(pair[1]) | |
visited = set() | |
cost = 0 | |
# for each unvisited node, we should find | |
# the length of the component it belongs to | |
# and the calculate the cost. | |
for node in nodes: | |
if node not in visited: | |
l_c = dfs(visited, g, node, 0) | |
cost += c_lib + ((l_c - 1) * c_road) | |
# in case there're cities who weren't added to the graph | |
# because they had no adjecent cities (they are not present | |
# in the matrix given), we should add their cost also | |
isolated_cities = n - len(visited) | |
cost += isolated_cities * c_lib | |
return cost |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment