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.
classResult{/* * Complete the 'getCost' function below. * The function accepts a weighted graph defined by: * 1. gNodes: Number of nodes * 2. gFrom, gTo: Lists of nodes defining edges * 3. gWeight: Weights of the edges */// Edge class to store destination and weightstaticclassEdge{intdest,weight;publicEdge(intdest,intweight){this.dest=dest;this.weight=weight;}}// State class for priority queue (Dijkstra's)staticclassState{intnode,cost;publicState(intnode,intcost){this.node=node;this.cost=cost;}}publicstaticvoidgetCost(intgNodes,List<Integer>gFrom,List<Integer>gTo,List<Integer>gWeight){// Step 1: Build the graph using adjacency listList<List<Edge>>graph=newArrayList<>();for(inti=0;i<=gNodes;i++){graph.add(newArrayList<>());}for(inti=0;i<gFrom.size();i++){intu=gFrom.get(i);intv=gTo.get(i);intweight=gWeight.get(i);graph.get(u).add(newEdge(v,weight));graph.get(v).add(newEdge(u,weight));}// Step 2: Implement Dijkstra's algorithm to find the minimum "maximum edge weight"PriorityQueue<State>pq=newPriorityQueue<>(Comparator.comparingInt(s->s.cost));boolean[]visited=newboolean[gNodes+1];int[]minCosts=newint[gNodes+1];Arrays.fill(minCosts,Integer.MAX_VALUE);minCosts[1]=0;// Start from node 1pq.offer(newState(1,0));while(!pq.isEmpty()){Statecurrent=pq.poll();// Skip already visited nodesif(visited[current.node])continue;visited[current.node]=true;// Explore neighborsfor(Edgeedge:graph.get(current.node)){intmaxCost=Math.max(current.cost,edge.weight);// Update the max edge cost along the pathif(maxCost<minCosts[edge.dest]){minCosts[edge.dest]=maxCost;pq.offer(newState(edge.dest,maxCost));}}}// Step 3: Print the resultif(minCosts[gNodes]==Integer.MAX_VALUE){System.out.println("NO PATH EXISTS");}else{System.out.println(minCosts[gNodes]);}}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Jack goes to Rapture
You are viewing a single comment's thread. Return to all comments →
Java solution using Dijkstra's algo