Djikstra's algorithm for finding the shortest path in a weighted
graph from a designated vertex to all other vertices
- Let v0 be the designated vertex and v1, ..., vn the remaining
vertex. For each vertex create a 3-tuple of the form (vi,v0,weight)
where if <v0,vi> is an edge in the graph then weight is the
weight of that edge and if <v0,vi> is NOT an edge, weight =
infinity. Put the triples in a data structure that puts the smallest
weight triple first (for example, a TreeSet in java with the triple's
compareTo function looking primarily - but not exclusively - at the
weight in the triple or, perhaps, a minheap of triples ordered by the
weight).
- Get the lowest weight triple from the data structure. Let vc be
the first vertex in the triple.
- Do the following loop:
while(the data structure
of triples is not empty) {
For every
vertex v adjacent to vc {
newWeight=weight of the edge from v to vc+the weight in the triple vc
is in
if(newWeight< the weight in the triple v is in) {
remove the triple for v from the data structure of triples.
create a new triple of the form (v,vc,newWeight) and put
it in the data structure
}
add vc's triple to a collection holding already-processed triples.
Get the lowest weight triple remaining in the data structure.
Let vc be the vertex in that triple.
}
}
Move that last triple into
the collection holding already-processed triples.
4. The collection holding already-processed triples
contains a triple for each vertex (except v0) with the minimum weight
of a path from v0.
5. You can reconstruct the minimum path (in reverse)
that got you to any vertex v as follows:
Let v be the vertex that you want to
reconstruct the path for.
Get the triple <v,vi,w> for v.
println <v,vi> and the weight w
of the edge from v to vi
While (vi != v0) {
Get the triple containing
vi from the collection (say <vi,vj,w'>)
println <vi,vj>
and the weight w' of the edge from vi to vj
Let vi=vj
}