Data Str & Algorithm HW Solutions 71

Data Str & Algorithm HW Solutions 71 - if(D[v.dist...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
71 cost for f nding all of the shortest paths is no worse than the cost to f nd the shortest path between a speci f ed pair of vertices. 11.8 1 2 3 4 5 6 Initial 0 Process 4 2 0 5 0 1 1 1 0 Process 2 1 5 5 8 0 1 1 1 0 Process 3 1 5 5 8 0 1 1 1 0 Process 6 1 2 5 8 0 1 1 1 0 Process 5 1 2 5 8 0 1 1 1 0 Process 1 1 2 5 8 0 1 1 1 0 11.9 Store at each position of array D both the distance, and the neighbor through which the vertex is reached (the vertex’s parent in the DFS tree). At the end, print out the path, in reverse order back to the source. // Compute shortest path distances void Dijkstra(Graph* G, Rec D[], int s) { int i, v, w; for (int i=0; i<G->n(); i++) // Initialize D[i].dist = INFINITY; D[s].dist = 0; D[s].par = -1; // This is the root for (i=0; i<G->n(); i++) { // Process vertices v = minVertex(G, D);
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: if (D[v].dist == INFINITY) return; // Unreachable G->setMark(v, VISITED); for (w=G->first(v); w<G->n(); w = G->next(v,w)) if (D[w].dist > (D[v].dist + G->weight(v, w))) { D[w].dist = D[v].dist + G->weight(v, w); D[w].par = v; // w’s parent in the DFS is v } } // Print out the paths (in reverse order) for (i=0; i<G->n(); i++) { cout << "Path for " << i << ": "; for (t=i; D[t].par != -1; t = D[t].par) cout << t << " "; cout << s << "\n"; } } 11.10 Here is a pseudo-code sketch of the algorithm. Converting to C ++ is quite easy since the code is given in the book as described here....
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online