Printing Paths in Dijkstra's Shortest Path Algorithm
Last Updated : 23 Jul, 2025
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 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;