我对Dijkstra算法的实现有问题。 我用所有顶点(Node)和相对边(Edge)创建了图形。 当我运行方法computePath(节点源)时,它正确地将priorityQueue添加到它遇到的第一个节点但不是以下节点。通过这种方式,在第二次迭代中,它不会找到插入节点的边缘。
类Node是这样的:
public class Node implements Comparable<Node>{
public final String id;
public Vector <Edge> adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Node previous;
//here there are all the methods included compareTo(Node other)
类Edge就是这样:
public class Edge{
public final Nodo target;
public final double weight;
//here there all the methods
分配所有方法的Edge的功能如下:
Vector <Arch> totArchs = this.getArchs();
for(int i=0;i<this.getNodes().size();i++)
this.getNodes().get(i).setAdjacenies(this.trovaAdiacenze(this.getNodes().get(i),totArchs));
,其中
public Vector <Edge> trovaAdiacenze(Node n,Vector <Arch> archs){
Vector <Edge> adiacenze = new Vector <Edge>();
for(int i=0;i<archs.size();i++){
if(n.getId().equalsIgnoreCase(archs.get(i).getInitialNode().getId()))
Edge e = new Edge(archs.get(i).getFinalNode(),archs.get(i).getCost());
adiacenze.add(e);}
}
return adiacenze;}
computePath方法的代码是
public static void computePaths(Node source){
source.minDistance = 0.;
PriorityQueue<Node> vertexQueue = new PriorityQueue<Node>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()){
Node u = vertexQueue.poll();
for (Edge e : u.adjacencies){
Node v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance)
{
vertexQueue.remove(v);
v.minDistance = distanceThroughU;
v.previous = u;
vertexQueue.add(v);
}
}
}
}
尽管节点具有所有正确的边缘,但实现并未找到第三个节点的邻接。
我可以用代码的输出更好地解释。
Added nodes:2 having 2 adjacencies
Added nodes:5 having 0 adjacencies
Added nodes:35 having 0 adjacencies
Added nodes:67 having 0 adjacencies
但是,在方法之外,它们有相邻性
for(Nodo n:ist.getNodes())
System.out.println("Node: "+n.id+ " having "+n.adjacencies.size()+" adjacencies");
,相对输出为
Node: 2 having 2 adjacencies
Node: 5 having 2 adjacencies
Node: 35 having 2 adjacencies
Node: 67 having 2 adjacencies
有人可以帮助我吗?