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.
publicstaticvoidsolve(intnodes,List<List<Integer>>input,intq,List<List<Integer>>queries)throwsIOException{//Using Floyd Warshall algorithm //https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/BufferedWriterwriter=newBufferedWriter(newPrintWriter(System.out));int[][]cost=newint[nodes+1][nodes+1];//Should have used value > 350, maybe 10000,//Because Integer.MAX_VALUE < (Integer.MAX_VALUE + int a) // because of overflow for(inti=0;i<nodes+1;i++){for(intj=0;j<nodes+1;j++){cost[i][j]=Integer.MAX_VALUE;if(j==i){cost[i][j]=0;}}}for(List<Integer>list:input){intstartNode=list.get(0);intdestNode=list.get(1);intweight=list.get(2);cost[startNode][destNode]=weight;}for(intk=1;k<nodes+1;k++){for(inti=1;i<nodes+1;i++){for(intj=1;j<nodes+1;j++){if(cost[i][k]!=Integer.MAX_VALUE&&cost[k][j]!=Integer.MAX_VALUE&&cost[i][j]>cost[i][k]+cost[k][j]){cost[i][j]=cost[i][k]+cost[k][j];}}}}for(List<Integer>query:queries){intstartNode=query.get(0);intdestNode=query.get(1);intlowestWeight=cost[startNode][destNode];if(lowestWeight==Integer.MAX_VALUE)lowestWeight=-1;writer.write(lowestWeight+"\n");}writer.flush();writer.close();}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<List<Integer>>input=newArrayList<>();IntStream.range(0,roadEdges).forEach(i->{try{String[]roadFromToWeight=bufferedReader.readLine().replaceAll("\\s+$","").split(" ");List<Integer>list=newArrayList<>();list.add(Integer.parseInt(roadFromToWeight[0]));list.add(Integer.parseInt(roadFromToWeight[1]));list.add(Integer.parseInt(roadFromToWeight[2]));input.add(list);}catch(IOExceptionex){thrownewRuntimeException(ex);}});intq=Integer.parseInt(bufferedReader.readLine().trim());List<List<Integer>>queries=newArrayList<>();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>query=newArrayList<>();query.add(x);query.add(y);queries.add(query);}catch(IOExceptionex){thrownewRuntimeException(ex);}});solve(roadNodes,input,q,queries);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 →
Java8 - Using Floyd Warshall algorithm