I was looking for dijkstra algorithm with java.
Below code works normally.
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);
}
}
}
}
why that vertexQueue.remove(v); occurs no error?
since we init the queue, we add something then poll.
so queue might be empty.
I thought remove operation occurs NoSuchElementException error.
but it operates normally.
and advice would be appreciated