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;
printPath(parent, parent[j]);
printf("%d ", j); }
Below is the complete implementation:
C++
#include<bits/stdc++.h>usingnamespacestd;// A C++ program for Dijkstra's// single source shortest path// algorithm. The program is for// adjacency matrix representation// of the graph.intNO_PARENT=-1;// Function to print shortest path// from source to currentVertex// using parents arrayvoidprintPath(intcurrentVertex,vector<int>parents){// Base case : Source node has// been processedif(currentVertex==NO_PARENT){return;}printPath(parents[currentVertex],parents);cout<<currentVertex<<" ";}// A utility function to print// the constructed distances// array and shortest pathsvoidprintSolution(intstartVertex,vector<int>distances,vector<int>parents){intnVertices=distances.size();cout<<"Vertex\t Distance\tPath";for(intvertexIndex=0;vertexIndex<nVertices;vertexIndex++){if(vertexIndex!=startVertex){cout<<"\n"<<startVertex<<" -> ";cout<<vertexIndex<<" \t\t ";cout<<distances[vertexIndex]<<"\t\t";printPath(vertexIndex,parents);}}}// Function that implements Dijkstra's// single source shortest path// algorithm for a graph represented// using adjacency matrix// representationvoiddijkstra(vector<vector<int>>adjacencyMatrix,intstartVertex){intnVertices=adjacencyMatrix[0].size();// shortestDistances[i] will hold the// shortest distance from src to ivector<int>shortestDistances(nVertices);// added[i] will true if vertex i is// included / in shortest path tree// or shortest distance from src to// i is finalizedvector<bool>added(nVertices);// Initialize all distances as// INFINITE and added[] as falsefor(intvertexIndex=0;vertexIndex<nVertices;vertexIndex++){shortestDistances[vertexIndex]=INT_MAX;added[vertexIndex]=false;}// Distance of source vertex from// itself is always 0shortestDistances[startVertex]=0;// Parent array to store shortest// path treevector<int>parents(nVertices);// The starting vertex does not// have a parentparents[startVertex]=NO_PARENT;// Find shortest path for all// verticesfor(inti=1;i<nVertices;i++){// Pick the minimum distance vertex// from the set of vertices not yet// processed. nearestVertex is// always equal to startNode in// first iteration.intnearestVertex=-1;intshortestDistance=INT_MAX;for(intvertexIndex=0;vertexIndex<nVertices;vertexIndex++){if(!added[vertexIndex]&&shortestDistances[vertexIndex]<shortestDistance){nearestVertex=vertexIndex;shortestDistance=shortestDistances[vertexIndex];}}// Mark the picked vertex as// processedadded[nearestVertex]=true;// Update dist value of the// adjacent vertices of the// picked vertex.for(intvertexIndex=0;vertexIndex<nVertices;vertexIndex++){intedgeDistance=adjacencyMatrix[nearestVertex][vertexIndex];if(edgeDistance>0&&((shortestDistance+edgeDistance)<shortestDistances[vertexIndex])){parents[vertexIndex]=nearestVertex;shortestDistances[vertexIndex]=shortestDistance+edgeDistance;}}}printSolution(startVertex,shortestDistances,parents);}// Driver Codeintmain(){vector<vector<int>>adjacencyMatrix={{0,4,0,0,0,0,0,8,0},{4,0,8,0,0,0,0,11,0},{0,8,0,7,0,4,0,0,2},{0,0,7,0,9,14,0,0,0},{0,0,0,9,0,10,0,0,0},{0,0,4,0,10,0,2,0,0},{0,0,0,14,0,2,0,1,6},{8,11,0,0,0,0,1,0,7},{0,0,2,0,0,0,6,7,0}};dijkstra(adjacencyMatrix,3);return0;}
Java
// A Java program for Dijkstra's// single source shortest path // algorithm. The program is for// adjacency matrix representation// of the graph.classDijkstrasAlgorithm{privatestaticfinalintNO_PARENT=-1;// Function that implements Dijkstra's// single source shortest path// algorithm for a graph represented // using adjacency matrix// representationprivatestaticvoiddijkstra(int[][]adjacencyMatrix,intstartVertex){intnVertices=adjacencyMatrix[0].length;// shortestDistances[i] will hold the// shortest distance from src to iint[]shortestDistances=newint[nVertices];// added[i] will true if vertex i is// included / in shortest path tree// or shortest distance from src to // i is finalizedboolean[]added=newboolean[nVertices];// Initialize all distances as // INFINITE and added[] as falsefor(intvertexIndex=0;vertexIndex<nVertices;vertexIndex++){shortestDistances[vertexIndex]=Integer.MAX_VALUE;added[vertexIndex]=false;}// Distance of source vertex from// itself is always 0shortestDistances[startVertex]=0;// Parent array to store shortest// path treeint[]parents=newint[nVertices];// The starting vertex does not // have a parentparents[startVertex]=NO_PARENT;// Find shortest path for all // verticesfor(inti=1;i<nVertices;i++){// Pick the minimum distance vertex// from the set of vertices not yet// processed. nearestVertex is // always equal to startNode in // first iteration.intnearestVertex=-1;intshortestDistance=Integer.MAX_VALUE;for(intvertexIndex=0;vertexIndex<nVertices;vertexIndex++){if(!added[vertexIndex]&&shortestDistances[vertexIndex]<shortestDistance){nearestVertex=vertexIndex;shortestDistance=shortestDistances[vertexIndex];}}// Mark the picked vertex as// processedadded[nearestVertex]=true;// Update dist value of the// adjacent vertices of the// picked vertex.for(intvertexIndex=0;vertexIndex<nVertices;vertexIndex++){intedgeDistance=adjacencyMatrix[nearestVertex][vertexIndex];if(edgeDistance>0&&((shortestDistance+edgeDistance)<shortestDistances[vertexIndex])){parents[vertexIndex]=nearestVertex;shortestDistances[vertexIndex]=shortestDistance+edgeDistance;}}}printSolution(startVertex,shortestDistances,parents);}// A utility function to print // the constructed distances// array and shortest pathsprivatestaticvoidprintSolution(intstartVertex,int[]distances,int[]parents){intnVertices=distances.length;System.out.print("Vertex\t Distance\tPath");for(intvertexIndex=0;vertexIndex<nVertices;vertexIndex++){if(vertexIndex!=startVertex){System.out.print("\n"+startVertex+" -> ");System.out.print(vertexIndex+" \t\t ");System.out.print(distances[vertexIndex]+"\t\t");printPath(vertexIndex,parents);}}}// Function to print shortest path// from source to currentVertex// using parents arrayprivatestaticvoidprintPath(intcurrentVertex,int[]parents){// Base case : Source node has// been processedif(currentVertex==NO_PARENT){return;}printPath(parents[currentVertex],parents);System.out.print(currentVertex+" ");}// Driver Codepublicstaticvoidmain(String[]args){int[][]adjacencyMatrix={{0,4,0,0,0,0,0,8,0},{4,0,8,0,0,0,0,11,0},{0,8,0,7,0,4,0,0,2},{0,0,7,0,9,14,0,0,0},{0,0,0,9,0,10,0,0,0},{0,0,4,0,10,0,2,0,0},{0,0,0,14,0,2,0,1,6},{8,11,0,0,0,0,1,0,7},{0,0,2,0,0,0,6,7,0}};dijkstra(adjacencyMatrix,0);}}// This code is contributed by Harikrishnan Rajan
Python3
importsysNO_PARENT=-1defdijkstra(adjacency_matrix,start_vertex):n_vertices=len(adjacency_matrix[0])# shortest_distances[i] will hold the# shortest distance from start_vertex to ishortest_distances=[sys.maxsize]*n_vertices# added[i] will true if vertex i is# included in shortest path tree# or shortest distance from start_vertex to # i is finalizedadded=[False]*n_vertices# Initialize all distances as # INFINITE and added[] as falseforvertex_indexinrange(n_vertices):shortest_distances[vertex_index]=sys.maxsizeadded[vertex_index]=False# Distance of source vertex from# itself is always 0shortest_distances[start_vertex]=0# Parent array to store shortest# path treeparents=[-1]*n_vertices# The starting vertex does not # have a parentparents[start_vertex]=NO_PARENT# Find shortest path for all # verticesforiinrange(1,n_vertices):# Pick the minimum distance vertex# from the set of vertices not yet# processed. nearest_vertex is # always equal to start_vertex in # first iteration.nearest_vertex=-1shortest_distance=sys.maxsizeforvertex_indexinrange(n_vertices):ifnotadded[vertex_index]andshortest_distances[vertex_index]<shortest_distance:nearest_vertex=vertex_indexshortest_distance=shortest_distances[vertex_index]# Mark the picked vertex as# processedadded[nearest_vertex]=True# Update dist value of the# adjacent vertices of the# picked vertex.forvertex_indexinrange(n_vertices):edge_distance=adjacency_matrix[nearest_vertex][vertex_index]ifedge_distance>0andshortest_distance+edge_distance<shortest_distances[vertex_index]:parents[vertex_index]=nearest_vertexshortest_distances[vertex_index]=shortest_distance+edge_distanceprint_solution(start_vertex,shortest_distances,parents)# A utility function to print # the constructed distances# array and shortest pathsdefprint_solution(start_vertex,distances,parents):n_vertices=len(distances)print("Vertex\t Distance\tPath")forvertex_indexinrange(n_vertices):ifvertex_index!=start_vertex:print("\n",start_vertex,"->",vertex_index,"\t\t",distances[vertex_index],"\t\t",end="")print_path(vertex_index,parents)# Function to print shortest path# from source to current_vertex# using parents arraydefprint_path(current_vertex,parents):# Base case : Source node has# been processedifcurrent_vertex==NO_PARENT:returnprint_path(parents[current_vertex],parents)print(current_vertex,end=" ")# Driver codeif__name__=='__main__':adjacency_matrix=[[0,4,0,0,0,0,0,8,0],[4,0,8,0,0,0,0,11,0],[0,8,0,7,0,4,0,0,2],[0,0,7,0,9,14,0,0,0],[0,0,0,9,0,10,0,0,0],[0,0,4,14,10,0,2,0,0],[0,0,0,0,0,2,0,1,6],[8,11,0,0,0,0,1,0,7],[0,0,2,0,0,0,6,7,0]]dijkstra(adjacency_matrix,0)
C#
// C# program for Dijkstra's // single source shortest path // algorithm. The program is for // adjacency matrix representation // of the graph. usingSystem;publicclassDijkstrasAlgorithm{privatestaticreadonlyintNO_PARENT=-1;// Function that implements Dijkstra's // single source shortest path // algorithm for a graph represented // using adjacency matrix // representation privatestaticvoiddijkstra(int[,]adjacencyMatrix,intstartVertex){intnVertices=adjacencyMatrix.GetLength(0);// shortestDistances[i] will hold the // shortest distance from src to i int[]shortestDistances=newint[nVertices];// added[i] will true if vertex i is // included / in shortest path tree // or shortest distance from src to // i is finalized bool[]added=newbool[nVertices];// Initialize all distances as // INFINITE and added[] as false for(intvertexIndex=0;vertexIndex<nVertices;vertexIndex++){shortestDistances[vertexIndex]=int.MaxValue;added[vertexIndex]=false;}// Distance of source vertex from // itself is always 0 shortestDistances[startVertex]=0;// Parent array to store shortest // path tree int[]parents=newint[nVertices];// The starting vertex does not // have a parent parents[startVertex]=NO_PARENT;// Find shortest path for all // vertices for(inti=1;i<nVertices;i++){// Pick the minimum distance vertex // from the set of vertices not yet // processed. nearestVertex is // always equal to startNode in // first iteration. intnearestVertex=-1;intshortestDistance=int.MaxValue;for(intvertexIndex=0;vertexIndex<nVertices;vertexIndex++){if(!added[vertexIndex]&&shortestDistances[vertexIndex]<shortestDistance){nearestVertex=vertexIndex;shortestDistance=shortestDistances[vertexIndex];}}// Mark the picked vertex as // processed added[nearestVertex]=true;// Update dist value of the // adjacent vertices of the // picked vertex. for(intvertexIndex=0;vertexIndex<nVertices;vertexIndex++){intedgeDistance=adjacencyMatrix[nearestVertex,vertexIndex];if(edgeDistance>0&&((shortestDistance+edgeDistance)<shortestDistances[vertexIndex])){parents[vertexIndex]=nearestVertex;shortestDistances[vertexIndex]=shortestDistance+edgeDistance;}}}printSolution(startVertex,shortestDistances,parents);}// A utility function to print // the constructed distances // array and shortest paths privatestaticvoidprintSolution(intstartVertex,int[]distances,int[]parents){intnVertices=distances.Length;Console.Write("Vertex\t Distance\tPath");for(intvertexIndex=0;vertexIndex<nVertices;vertexIndex++){if(vertexIndex!=startVertex){Console.Write("\n"+startVertex+" -> ");Console.Write(vertexIndex+" \t\t ");Console.Write(distances[vertexIndex]+"\t\t");printPath(vertexIndex,parents);}}}// Function to print shortest path // from source to currentVertex // using parents array privatestaticvoidprintPath(intcurrentVertex,int[]parents){// Base case : Source node has // been processed if(currentVertex==NO_PARENT){return;}printPath(parents[currentVertex],parents);Console.Write(currentVertex+" ");}// Driver Code publicstaticvoidMain(String[]args){int[,]adjacencyMatrix={{0,4,0,0,0,0,0,8,0},{4,0,8,0,0,0,0,11,0},{0,8,0,7,0,4,0,0,2},{0,0,7,0,9,14,0,0,0},{0,0,0,9,0,10,0,0,0},{0,0,4,0,10,0,2,0,0},{0,0,0,14,0,2,0,1,6},{8,11,0,0,0,0,1,0,7},{0,0,2,0,0,0,6,7,0}};dijkstra(adjacencyMatrix,0);}}// This code has been contributed by 29AjayKumar
JavaScript
constNO_PARENT=-1;functiondijkstra(adjacencyMatrix,startVertex){constnVertices=adjacencyMatrix[0].length;// shortestDistances[i] will hold the shortest distance from startVertex to iconstshortestDistances=newArray(nVertices).fill(Number.MAX_SAFE_INTEGER);// added[i] will true if vertex i is included in shortest path tree// or shortest distance from startVertex to i is finalizedconstadded=newArray(nVertices).fill(false);// Initialize all distances as infinite and added[] as falsefor(letvertexIndex=0;vertexIndex<nVertices;vertexIndex++){shortestDistances[vertexIndex]=Number.MAX_SAFE_INTEGER;added[vertexIndex]=false;}// Distance of source vertex from itself is always 0shortestDistances[startVertex]=0;// Parent array to store shortest path treeconstparents=newArray(nVertices).fill(NO_PARENT);// The starting vertex does not have a parentparents[startVertex]=NO_PARENT;// Find shortest path for all verticesfor(leti=1;i<nVertices;i++){// Pick the minimum distance vertex from the set of vertices not yet processed.// nearestVertex is always equal to startVertex in first iteration.letnearestVertex=-1;letshortestDistance=Number.MAX_SAFE_INTEGER;for(letvertexIndex=0;vertexIndex<nVertices;vertexIndex++){if(!added[vertexIndex]&&shortestDistances[vertexIndex]<shortestDistance){nearestVertex=vertexIndex;shortestDistance=shortestDistances[vertexIndex];}}// Mark the picked vertex as processedadded[nearestVertex]=true;// Update dist value of the adjacent vertices of the picked vertex.for(letvertexIndex=0;vertexIndex<nVertices;vertexIndex++){constedgeDistance=adjacencyMatrix[nearestVertex][vertexIndex];if(edgeDistance>0&&shortestDistance+edgeDistance<shortestDistances[vertexIndex]){parents[vertexIndex]=nearestVertex;shortestDistances[vertexIndex]=shortestDistance+edgeDistance;}}}printSolution(startVertex,shortestDistances,parents);}// A utility function to print the constructed distances array and shortest pathsfunctionprintSolution(startVertex,distances,parents){constnVertices=distances.length;console.log("Vertex\t Distance\tPath");for(letvertexIndex=0;vertexIndex<nVertices;vertexIndex++){if(vertexIndex!==startVertex){process.stdout.write(`\n ${startVertex} -> ${vertexIndex}\t\t ${distances[vertexIndex]}\t\t`);printPath(vertexIndex,parents);}}}// Function to print shortest path from source to currentVertex using parents arrayfunctionprintPath(currentVertex,parents){// Base case: Source node has been processedif(currentVertex===NO_PARENT){return;}printPath(parents[currentVertex],parents);process.stdout.write(`${currentVertex} `);}// Driver codeconstadjacencyMatrix=[[0,4,0,0,0,0,0,8,0],[4,0,8,0,0,0,0,11,0],[0,8,0,7,0,4,0,0,2],[0,0,7,0,9,14,0,0,0],[0,0,0,9,0,10,0,0,0],[0,0,4,14,10,0,2,0,0],[0,0,0,0,0,2,0,1,6],[8,11,0,0,0,0,1,0,7],[0,0,2,0,0,0,6,7,0]];dijkstra(adjacencyMatrix,0);