我一直在这个问题上停留,没有取得任何进展。我想以成功的“最短路径”遍历(ala Dijkstra的算法)查找并打印出FIRST节点。如在第一个选择访问指定节点的路径中。我觉得我需要一个数据结构,也许是一个ArrayList?我已经尝试过了,但是我似乎无法将它作为经过的节点的简明清单。
我的代码:
public static ShortestPaths runDijkstra(Map<String,Node> graph, Node startNode) {
//Queue for visited nodes
Queue<Node> unvisitedNodes = new LinkedList<>();
//Distance of node from source
Map<Node,Integer> distances = new HashMap<>();
//Current node w/previous node in optimal path
Map<Node,Node> previousNode = new HashMap<>();
for(Node n : graph.values()) {
//Fill collections
distances.put(n, Integer.MAX_VALUE);
previousNode.put(n, null);
unvisitedNodes.add(n);
}
//Set source node distance to 0
distances.put(startNode, 0);
while(!unvisitedNodes.isEmpty()) {
int lowestDistance = Integer.MAX_VALUE;
Node current = null;
for(Node n : unvisitedNodes) {
if(distances.get(n) < lowestDistance) {
lowestDistance = distances.get(n);
current = n;
}
}
unvisitedNodes.remove(current);
for(Entry<Node,Integer> neighborEntry : current.adjacentNodes.entrySet()) {
int distanceFromNeighborToSource = (distances.get(current) + neighborEntry.getValue());
Node neighbor = neighborEntry.getKey();
if(distanceFromNeighborToSource < distances.get(neighborEntry.getKey())) {
distances.put(neighbor, distanceFromNeighborToSource);
previousNode.put(neighbor, current);
}
}
}
previousNode.put(startNode, new Node("-"));
return new ShortestPaths(distances, previousNode);
}