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.
# base case when building a lib is cheaper than a road
if c_lib <= c_road:
return n*c_lib
# case when have to build roads
# initialize array to keep track of visited cities
# 'w' not visited
# 'g' being visited
# 'b' finished visiting
visited = ['w'] * (n+1)
# initialize dictionary with all cities as keys
adj = {}
for city in range(1, n+1):
adj[city] = []
# fill in the dictionary by recording adjacencies
for pair in cities:
c1 = pair[0]
c2 = pair[1]
# record cities as adjacent
adj[c1].append(c2)
adj[c2].append(c1)
# integer list of components with ints representing their sizes
components = []
# depth first search
def dfs(city, count):
this_count = 1
visited[city] = 'g'
# go through all adjacent cities
for adjacent in adj[city]:
# if city has not been visited before
if visited[adjacent] == 'w':
# run dfs on that city
this_count += dfs(adjacent, count)
# finished visiting this city
visited[city] = 'b'
return this_count
for city in range(1, n+1):
if visited[city] == 'b':
continue
count = 0
count = dfs(city, count)
components.append(count)
print(components)
cost = c_lib * len(components)
for comp in components:
cost += (comp-1)*c_road
return cost
'''
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Roads and Libraries
You are viewing a single comment's thread. Return to all comments →
python solution
'''