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.
defroadsAndLibraries(n,c_lib,c_road,cities):# if libraries are cheaper we dont need to build roadsifc_lib<c_road:returnc_lib*nvisited=[0]*ntransport_stack=[]cities_map=defaultdict(set)islands=0# create a graph of road destinations# add both ways for bidirectional pathsforiincities:cities_map[i[0]-1].add(i[1]-1)cities_map[i[1]-1].add(i[0]-1)# iterate over the list of road edgesforcityincities_map:ifvisited[city]:continue# if we have never been at this city before it is a new islandislands+=1transport_stack.append(city)# travel the path of the road# if we find a new city add it to the stackwhiletransport_stack:new_destination=transport_stack.pop(-1)ifnotvisited[new_destination]:visited[new_destination]=1ifnew_destinationincities_map:fordestinationincities_map[new_destination]:ifnotvisited[destination]:transport_stack.append(destination)# if we nevered visited after looking at all the roads then it must be an island islands+=n-sum(visited)roads=n-islands# we need 1 road per city and 1 library per islandresult=(roads*c_road)+(c_lib*islands)returnresult
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 →