简体   繁体   中英

How to implement the priority queue in Dijkstra's algorithm

Dijkstra's algorithm uses a priority queue which is ordered by the distances from the starting point, however the distances of the vertices are changeing during the algorithm. I am not sure when does the priority queue reorder itself but if I have the following comparator:

struct compareByDistance
{
bool operator()(Vertex const &a, Vertex const &b)
    {
        return( getDistance(a) < getDistance(b) );
    }  
};

During the algorithm we only delete values from the queue, so I can't imagine that it will fully reorder itself. Therefore if a distance value changes than the queue won't be in the order of the distances.

How do you implement it similarly to this?

Google min-max(usually default) heap, it will work as a priority queue. Where you always pop the element at the top. Which will be the node with the smallest distance.

One possible solution is to have a visited array which keeps track of all nodes to which least distance has been found(ie they have been popped out of the queue once). Every time you pop an item out of the queue, check the visited array to see if the node's shortest distance has been found. If it has been then, ignore that element. The code would look like:-

while(!queue.empty())
{
node n1= queue.top();
queue.pop();
if(visited[n1]) continue;

////
//Rest of the code here
////
}

Note: This might not be the most optimal solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM