gpt4 book ai didi

java - 打印前人的 Dijkstra 算法

转载 作者:行者123 更新时间:2023-12-02 01:02:38 24 4
gpt4 key购买 nike

我正在尝试打印 Dijkstra 算法,但目前仅从我的 getPath() 方法打印目标 ID。我的想法是从目标顶点向后工作并打印每个前导顶点,直到打印起始顶点。如果有另一种方法来存储/打印路径,我将非常愿意尝试不同的方式,我很欣赏任何想法!

class ShortestPathFinder {
private Graph graph = new Graph();
private Vertex source = new Vertex(0, null);
private Vertex destination = new Vertex(0,null);

private Map<Vertex,Vertex> previousVertex = new HashMap();
private Set<Vertex> visited = new HashSet();

public Optional<Path> findShortestPath(Graph graph, Vertex source, Vertex destination, ReadInput graphReader) {

this.destination = destination;
this.source = source;
Optional<Path> pathFound = Optional.empty();
source.setDistanceFromSource(0);
PriorityQueue<Vertex> priorityQueue = new PriorityQueue<>();
priorityQueue.add(source);
source.setVisited(true);
boolean destinationFound = false;

while( !priorityQueue.isEmpty() && destinationFound == false){
// Getting the minimum distance vertex from priority queue
Vertex actualVertex = priorityQueue.poll();
System.out.println("working on: " + actualVertex.getID());

actualVertex = graphReader.SetAdjList(actualVertex);

for(Edge edge : actualVertex.getAdjacenciesList()){
Vertex v = edge.getTargetVertex();
System.out.println("a Neighbor is: " + v.getID());
if(!v.isVisited()) {
if(v.getID() == destination.getID()) {
System.out.println("Destination found");
Path path = new Path(previousVertex);
pathFound = Optional.of(path);
destinationFound = true;
break;
}
double newDistance = actualVertex.getDistanceFromSource() + edge.getWeight();

if( newDistance < v.getDistanceFromSource() ){
priorityQueue.remove(v);
v.setDistanceFromSource(newDistance);
v.setPredecessor(actualVertex);
priorityQueue.add(v);
System.out.println("Added: " + v.getID());
}
}
}
actualVertex.setVisited(true);
}
return pathFound;
}

public List<Vertex> getPath() {
List<Vertex> path = new ArrayList<>();

for(Vertex vertex=destination;vertex!=null;vertex=vertex.getPredecessor()){
path.add(vertex);
}
Collections.reverse(path);
return path;

}
}

最佳答案

到达目的地时,将调用代码中的以下部分:

                    if(v.getID() == destination.getID()) {
System.out.println("Destination found");
Path path = new Path(previousVertex);
pathFound = Optional.of(path);
destinationFound = true;
break;
}

相应的 v 从未设置过其前任,这是您的 getPath() 方法所依赖的。考虑在 if 语句中设置它,如下所示:

                    if(v.getID() == destination.getID()) {
System.out.println("Destination found");
destination.setPredecessor(actualVertex); // sets the predecessor for backwards traversal
Path path = new Path(previousVertex);
pathFound = Optional.of(path);
destinationFound = true;
break;
}

关于java - 打印前人的 Dijkstra 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60469671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com