我正在寻找带有java的dijkstra算法。
下面的代码正常工作。
public static void computePaths(Vertex source, Subway p, int broken)
{
//set the source vertex distance to 0 (as distance source->source=0)
source.minDistance=0;
//init queue , add source to keep track of nodes visited (cloud)
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
//keep track of total vertices tracked so as not to go in circles
List<Integer> l=new LinkedList<Integer>();
// while the cloud is not empty
while (!vertexQueue.isEmpty()) {
// take the head as u and...
Vertex u = vertexQueue.poll();
//(add position of u to the tracking list)
l.add(new Integer(u.pos));
// ...Visit each edge exiting u
Iterator<Edge> it=(p.subwayNetwork.getEdges(u.pos)).iterator();
while (it.hasNext())
{
Edge e= it.next();
Vertex v = e.dest;
Double weight = e.weight;
// calculate the distance from u to the node v
Double distanceThroughU = u.minDistance + weight;
// if the distance is less then the min. distance, and not already visited, and neither
// the vertice and edge are broken
if (distanceThroughU < v.minDistance && !l.contains(v.pos) && v.pos!=broken && !e.broken) {
//remove the node form the queue and update the distance and prev. value
vertexQueue.remove(v);
//update the distance
v.minDistance=distanceThroughU;
//update the path visited till now
v.previous = u;
//reenter the node with the new distance
vertexQueue.add(v);
}
}
}
}
为什么vertexQueue.remove(v);
没有出错?
因为我们启动队列,所以我们添加一些东西然后轮询。
所以队列可能是空的。
我以为删除操作发生NoSuchElementException错误。
但它运作正常。
和建议将不胜感激
答案 0 :(得分:1)
remove() - 方法将bool作为返回值。 它返回&#34; true&#34;如果队列因调用而改变,否则返回&#34; false&#34;,但没有异常!
来源:https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html#remove(java.lang.Object)