I'm trying to implement the dijkstra algorithm with priority queue, but I can't understand how it works. I read many guide on the web but I can't understand this algorithm at all.
My question are: what is the priority for each node? I think that it is the weight of the incoming edge with minimun value, but I'm not sure. Is this true?
Second question, when I extract the root of the queue, how works if this node is not adjacency with no one of the visited nodes?
You should use
priority queue
where thevertex
with the shortest distance from the startingvertex
will get the highest priority. Initially, allvertices
will have the shortest distance of infinity and the startingvertex
will have the shortest distance 0.Start by inserting of all
vertices
(with itsedges
) from the graph inside thePQ
. Removevertex
from thePQ
and explore all itsedges
. Compare the shortest distances with all adjacentvertices
and if any distance is less than the shortest distance on the currentvertex
, update adjacentvertex
shortest distance inside thePQ
. Continue whilePQ
is not empty.Vertices
which got noedges
will finish with the shortest distance of infinity because it is not possible 'get to them' from the startingvertex
. However, they will be still removed from thePQ
.Pseudocode
MIT OpenCourseWare Links:
Path problems overview
Dijkstra