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.
Anyone who' doing it in java and using djisktra algo, it is possible.
Store the Graph in Hashmap , edges as well.
Store distances in hashmap
Use priority queue
Make a Node class for priority queue
Store the results in hashmap
In the main code, where reading of file is going on, start coding right from there so you don't have to iterate the loop again.
There are multiple edges. You have to save the latest entry.
If the source and distance is same return 0.
Run till priority is not empty or destination source is reached.
I used recursion.
It took me a week to solve as I did not clear priority queue for each new query.
So clear distances hashmap, queue etc before going for next query.
Heres the code, but please try it yourself, it took me a week, you can do it too.
15.
importjava.io.*;importjava.math.*;importjava.security.*;importjava.text.*;importjava.util.*;importjava.util.concurrent.*;importjava.util.function.*;importjava.util.regex.*;importjava.util.stream.*;importstaticjava.util.stream.Collectors.joining;importstaticjava.util.stream.Collectors.toList;publicclassSolution{staticPriorityQueue<Node>nodesToVisit=newPriorityQueue<>();staticclassNodeimplementsComparable<Node>{intvertex;intdistance=0;booleanvisited=false;publicNode(intvertex,intdistance){// vertexes.this.vertex=vertex;this.distance=distance;}@OverridepublicintcompareTo(Nodeother){returnInteger.compare(this.distance,other.distance);}@Overridepublicbooleanequals(Objectobj){if(this==obj)returntrue;if(obj==null||getClass()!=obj.getClass())returnfalse;Nodenode=(Node)obj;returnvertex==node.vertex;}@OverridepublicinthashCode(){returnObjects.hash(vertex);}@OverridepublicStringtoString(){return"{ Node : "+vertex+" Distance is: "+distance+" }";}}staticHashMap<List<Integer>,Integer>results=newHashMap<>();staticHashMap<Integer,HashMap<Integer,Integer>>adjacencyList2=newHashMap<>();staticHashSet<Integer>visited;publicstaticintshortestPathFinder(intsourceVertex,intdestination){intweight=0;// weight of current nodeif(sourceVertex==destination)returndistance.get(sourceVertex);if(!visited.contains(sourceVertex)){weight=distance.get(sourceVertex);// weight of the sourcefor(Map.Entry<Integer,Integer>edgeWithWeight:adjacencyList2.get(sourceVertex).entrySet()){//key is edge(neighbour) of source and value is the weight of the edge// updating distances to all neighboursweight+=edgeWithWeight.getValue();// weight of negihbour edge intneighbourExistingWeight=300000;if(distance.containsKey(edgeWithWeight.getKey()))neighbourExistingWeight=distance.get(edgeWithWeight.getKey());if(neighbourExistingWeight>weight){// neighrbour ka existing weight checkdistance.put(edgeWithWeight.getKey(),weight);Nodenode=newNode(edgeWithWeight.getKey(),distance.get(edgeWithWeight.getKey()));// if (nodesToVisit.contains(node)) {// nodesToVisit.remove(node);// }nodesToVisit.add(node);}weight=distance.get(sourceVertex);// weight of the source}}visited.add(sourceVertex);if(nodesToVisit.isEmpty())return-1;returnshortestPathFinder(nodesToVisit.remove().vertex,destination);}staticHashMap<Integer,Integer>distance=newHashMap<>();publicstaticvoidmain(String[]args)throwsIOException{BufferedReaderbufferedReader=newBufferedReader(newInputStreamReader(System.in));String[]roadNodesEdges=bufferedReader.readLine().replaceAll("\\s+$","").split(" ");introadNodes=Integer.parseInt(roadNodesEdges[0]);introadEdges=Integer.parseInt(roadNodesEdges[1]);// List<Integer> roadFrom = new ArrayList<>();// List<Integer> roadTo = new ArrayList<>();// List<Integer> roadWeight = new ArrayList<>();// int startNode, endNode, weight;IntStream.range(0,roadEdges).forEach(i->{try{String[]roadFromToWeight=bufferedReader.readLine().replaceAll("\\s+$","").split(" ");// roadFrom.add(Integer.parseInt(roadFromToWeight[0]));// roadTo.add(Integer.parseInt(roadFromToWeight[1]));// roadWeight.add(Integer.parseInt(roadFromToWeight[2]));intstartNode=Integer.parseInt(roadFromToWeight[0]);intendNode=Integer.parseInt(roadFromToWeight[1]);intweight=Integer.parseInt(roadFromToWeight[2]);HashMap<Integer,Integer>edgesAndWeight=newHashMap<>();edgesAndWeight.put(endNode,weight);if(adjacencyList2.containsKey(startNode)){edgesAndWeight=adjacencyList2.get(startNode);edgesAndWeight.put(endNode,weight);}else{adjacencyList2.put(startNode,edgesAndWeight);}if(!adjacencyList2.containsKey(endNode)){adjacencyList2.put(endNode,newHashMap<>());}}catch(IOExceptionex){thrownewRuntimeException(ex);}});// System.out.println(adjacencyList2);intq=Integer.parseInt(bufferedReader.readLine().trim());HashMap<List<Integer>,Integer>results=newHashMap<>();IntStream.range(0,q).forEach(qItr->{try{String[]firstMultipleInput=bufferedReader.readLine().replaceAll("\\s+$","").split(" ");intx=Integer.parseInt(firstMultipleInput[0]);inty=Integer.parseInt(firstMultipleInput[1]);List<Integer>k=newArrayList<Integer>();// query pairk.add(x);k.add(y);intstartNode=x;intendNode=y;intshortestPath=-1;if(results.containsKey(k)){System.out.println(results.get(k));}elseif(startNode==endNode)System.out.println(0);else{visited=newHashSet<>();distance.clear();nodesToVisit.clear();//above is to clear any useless data and start new for new querydistance.put(startNode,0);shortestPath=shortestPathFinder(startNode,endNode);System.out.println(shortestPath);results.put(k,shortestPath);}}catch(IOExceptionex){thrownewRuntimeException(ex);}});bufferedReader.close();}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Floyd : City of Blinding Lights
You are viewing a single comment's thread. Return to all comments →