Example Node Priority QueuesThe following function implements Dijkstra's algorithm for computing
the shortest paths
in a The function In Remark: Notice that in the
#include <LEDA/graph/graph.h>
#include <LEDA/graph/node_pq.h>
using namespace leda;
void MY_DIJKSTRA(const graph& G,node s, const edge_array<int>& cost,
node_array<int>& dist, node_array<edge>& pred)
{
node_pq<int> PQ(G);
dist[s]=0;
PQ.insert(s,0);
node v;
forall_nodes(v,G) pred[v]=nil;
while (!PQ.empty()) {
node u=PQ.del_min();
edge e;
forall_adj_edges(e,u) {
v=G.opposite(u,e);
int c=dist[u]+cost[e];
if (pred[v]==nil&&v!=s) PQ.insert(v,c);
else if (c<dist[v]) PQ.decrease_p(v,c);
else continue;
dist[v]=c;pred[v]=e;
}
}
}
int main()
{
//create random graph and random edge weights
graph G;
random_graph(G,50,500);
random_source S(1,100);
edge_array<int> cost(G);
edge e;forall_edges(e,G) S>>cost[e];
//call MY_DIJKSTRA() with corresponding parameters
node s=G.first_node();
node_array<int> dist(G);
node_array<edge> pred(G);
MY_DIJKSTRA(G,s,cost,dist,pred);
//illustrate the result of MY_DIJKSTRA() for one target node t
node t=G.last_node();
if (pred[t]!=nil) { //There is a shortest path from s to t
std::cout << "The distance from ";
G.print_node(s);
std::cout << " to ";
G.print_node(t);
std::cout << " is " << dist[t] << std::endl;
std::cout << "The shortest path is ";
list<edge> L;
node current=t;
while (current!=s) { //compute shortest path from pred
L.push_front(pred[current]);
current=G.source(pred[current]);
}
forall(e,L) { //print shortest path
G.print_edge(e);
std::cout << " length " << cost[e] << std::endl;
}
}
else if (s==t) std::cout << "Source and target are identical";
else {
std::cout << "There is no path from ";
G.print_node(s);
std::cout << " to ";
G.print_node(t);
}
std::cout << std::endl;
return 0;
}
|
See also:Manual Entries: Manual Page Node Priority Queues |