作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试打印 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/
我是一名优秀的程序员,十分优秀!