简体   繁体   中英

dijkstra algorithm priority queue

When we are writing dijkstra algorithm with priority queue why we are not check about the visited node?

while (!pq.empty())
    {
        
        int u = pq.top().second;
        pq.pop();
 
        // Get all adjacent of u.
        for (auto x : adj[u])
        {
            int v = x.first;
            int weight = x.second;
 
            if (dist[v] > dist[u] + weight)
            {
                dist[v] = dist[u] + weight;
                pq.push(make_pair(dist[v], v));
            }
        }

It does check the previous value of the node in dist[v] , which I assume stores the current best distance from the root (or u ) to node v . If a new path is found to v which is shorter than the previous shortest one, it is reinserted into the priority queue because it may now provide shorter paths to other nodes. If this new distance to v is longer than the previous, then it is left alone. This is why there is no else in the implementation.

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