GFG App
Open App
Browser
Continue

# Printing Paths in Dijkstra’s Shortest Path Algorithm

Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given graph.
We have discussed Dijkstra’s Shortest Path algorithm in the below posts.

The implementations discussed above only find shortest distances, but do not print paths. In this post-printing of paths is discussed.

Example:

Input: Consider below graph and source as 0,

Graph Used in the problem

Output

Vertex     Distance    Path
0 -> 1          4        0 1
0 -> 2          12        0 1 2
0 -> 3          19        0 1 2 3
0 -> 4          21        0 7 6 5 4
0 -> 5          11        0 7 6 5
0 -> 6          9        0 7 6
0 -> 7          8        0 7
0 -> 8          14        0 1 2 8

The idea is to create a separate array parent[]. Value of parent[v] for a vertex v stores parent vertex of v in shortest path tree. The parent of the root (or source vertex) is -1. Whenever we find a shorter path through a vertex u, we make u as a parent of the current vertex.

Once we have the parent array constructed, we can print the path using the below recursive function.

void printPath(int parent[], int j)
{
// Base Case : If j is source
if (parent[j]==-1)
return;

printPath(parent, parent[j]);

printf("%d ", j);
}

Below is the complete implementation:

## Javascript

Output

Vertex     Distance    Path
0 -> 1          4        0 1
0 -> 2          12        0 1 2
0 -> 3          19        0 1 2 3
0 -> 4          21        0 7 6 5 4
0 -> 5          11        0 7 6 5
0 -> 6          9        0 7 6
0 -> 7          8        0 7
0 -> 8          14        0 1 2 8
Time Complexity:- O(V^2)
Space Complexity:- O(V^2)