Untitled
unknown
java
3 years ago
2.8 kB
3
Indexable
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'get_shortest_time' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
* 1. STRING startNode
* 2. STRING endNode
* 3. 2D_STRING_ARRAY paths
*/
public static long get_shortest_time(String startNode, String endNode, List<List<String>> paths) {
Map<String, List<IdAndLen>> edges = new HashMap<>();
for(List<String> path : paths) {
List<IdAndLen> neighbors = edges.getOrDefault(path.get(0), new ArrayList<>());
neighbors.add(new IdAndLen(path.get(1), Long.parseLong(path.get(2))));
edges.put(path.get(0), neighbors);
}
// printMap(edges);
PriorityQueue<PathlenAndId> pq = new PriorityQueue(10, (o1, o2) -> {
if (((PathlenAndId)o1).pathlen < ((PathlenAndId)o2).pathlen) {
return -1;
} else if (((PathlenAndId)o1).pathlen == ((PathlenAndId)o2).pathlen) {
return 0;
} else {
return 1;
}
});
if (edges.get(startNode) != null) {
pq.add(new PathlenAndId(0, startNode));
}
Set<String> visitedNode = new HashSet<>();
while (!pq.isEmpty()) {
PathlenAndId node = pq.remove();
if (visitedNode.contains(node.id)) {
continue;
}
if (node.id == endNode) {
return node.pathlen;
}
visitedNode.add(node.id);
for(IdAndLen edge : edges.getOrDefault(node.id, new ArrayList<>())) {
pq.add(new PathlenAndId(node.pathlen + edge.edgeLen, edge.id));
}
}
return -1;
}
static class PathlenAndId {
public long pathlen;
public String id;
public PathlenAndId(long pathlen, String id) {
this.pathlen = pathlen;
this.id = id;
}
public String toString() {
return "(id:" + this.id + ", " + "pathLen:" + this.pathlen + ")";
}
}
static class IdAndLen {
public String id;
public long edgeLen;
public IdAndLen(String id, long edgeLen) {
this.id = id;
this.edgeLen = edgeLen;
}
public String toString() {
return "(id:" + this.id + ", " + "len:" + this.edgeLen + ")";
}
}
}
Editor is loading...