0

I started to implement Graphs algorithms and I don't know how to print the path from the source to destination for this Dijkstra implementation ? Thank you

#define INF 0x3f3f3f3f
typedef pair<int,int> ii;  // to vertex, weight
typedef vector<ii> vii;    // from source to vertexes with weight
typedef vector<vii> graph;  // graph

graph gg;
vector<int> Dist;

void Dijikstra(int source, int N){
    priority_queue<ii, vii, greater<ii>> Q;
    Dist.assign(N,INF);
    Dist[source] = 0;
    Q.push(make_pair(0,source));
    while (!Q.empty())
    {
        ii front = Q.top(); Q.pop();
        int d = front.first, u = front.second;
        if(d > Dist[u]) continue;
        for (int i = 0; i < gg[u].size(); i++)
        {
            ii v = gg[u][i];
            if(Dist[u]+v.second < Dist[v.first]){
                Dist[v.first]  = Dist[u] + v.second;
                Q.push(ii(Dist[v.first],v.first));          
            }
        }
    }
}
jbsu32
  • 1,036
  • 1
  • 11
  • 31

2 Answers2

1

The pseudocode of Dijkstra's algorithm:

function Dijkstra(Graph, source):
    create vertex set Q
    for each vertex v in Graph:  // Initialization
        dist[v] ← INFINITY       // Unknown distance from source to v
        prev[v] ← UNDEFINED      // Previous node in optimal path from source
        add v to Q               // All nodes initially in Q (unvisited nodes)
    dist[source] ← 0             // Distance from source to source
    while Q is not empty:
        u ← vertex in Q with min dist[u]  // Node with the least distance will be selected first
        remove u from Q     
        for each neighbor v of u:         // where v is still in Q.
            alt ← dist[u] + length(u, v)
            if alt < dist[v]:             // A shorter path to v has been found
                dist[v] ← alt 
                prev[v] ← u 
     return dist[], prev[]

Reconstruct the path:

S ← empty sequence
u ← target
while prev[u] is defined:           // Construct the shortest path with a stack S
    insert u at the beginning of S  // Push the vertex onto the stack
    u ← prev[u]                     // Traverse from target to source
insert u at the beginning of S      // Push the source onto the stack
Huy Vo
  • 2,418
  • 6
  • 22
  • 43
0

With dijkstra, each time you add a node to your 'visited set' you set that nodes 'parent' or 'origin', i.e. the node from the visited set through which it was added. Once you have reached your target node, you start there and move back up the parents, until you're back at your source.

You could start by printing this sequence, or if you're looking for a more visual approach, you could have a look at the graphviz set of tools and libraries.

Lanting
  • 3,060
  • 12
  • 28