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.
Here's in JS, with added comments and descriptive variable names to assist.
functionroadsAndLibraries(n,c_lib,c_road,cities){letspent=0;letconnects=newMap();letvisited=newMap();constunvisited=[];constregions=[];// Populate connections and build out unvisited stack;cities.forEach(city=>{constcityInd=city[0];constdest=city[1];unvisited.push(cityInd);connects.set(cityInd,connects.has(cityInd)?[...connects.get(cityInd),dest]:[dest]);connects.set(dest,connects.has(dest)?[...connects.get(dest),cityInd]:[cityInd]);});// recursive visitation, returns self and further explores connected unvisited citiesconstvisit=(current)=>{if(!visited.has(current)){visited.set(current,true);letcurrentRegion=[current];constneighs=connects.get(current);neighs.forEach((n)=>{currentRegion=[...currentRegion,...visit(n)];});returncurrentRegion;}return[];};// visits each node, if already visited in a preceeding exploration session, // skip, as already in established region, otherwise begin building out a new region.while(unvisited.length>0){constcurrent=unvisited.pop();if(!visited.has(current)){regions.push(visit(current));}}// Fill out cost of unconnected cities, i.e. cities which weren't given any neighbours in the input.// These all will be solo cities with their own library.for(leti=1;i<=n;i++){if(!connects.has(i)){spent+=c_lib;}}// Fill out the best case for each region, between one of two options,// either every city with their own library, or one library and all cities connected by one road to another.regions.forEach(r=>{constcostOfAllLibrary=c_lib*r.length;constcostOfOneLibraryWithRoads=c_lib+(r.length-1)*c_road;spent+=Math.min(costOfAllLibrary,costOfOneLibraryWithRoads);});returnspent;}
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 →
Here's in JS, with added comments and descriptive variable names to assist.