D'Esopo-Pape Algorithm : Single Source Shortest Path
Last Updated : 04 Jun, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report
Given an undirected weighted graph with v vertices labeled from 0 to v - 1, and a list of edges represented as a 2D array edges[][], where each entry is of the form [a, b, w] indicating an undirected edge between vertex a and vertex b with weight w. You are also given a source vertex src. The task is to compute the shortest paths from the source vertex to all other vertices in the graph.
Note: The graph is connected and doesn't contain any negative weight edge.
Output: [0, 5, 6, 7, 7] Explanation: Shortest Paths: For 0 to 1 minimum distance will be 5. By following path 0 → 1 For 0 to 2 minimum distance will be 6. By following path 0 → 1 → 2 For 0 to 3 minimum distance will be 7. By following path 0 → 1 → 3 For 0 to 4 minimum distance will be 7. By following path 0 → 1 → 2 → 4
For this problem, we’ve already explored both Dijkstra's algorithm and Bellman-Ford Algorithm. However, the D’Esopo-Pape Algorithm often performs better in practice across a wide range of cases. That said, there are certain scenarios, particularly with specific graph structures where its performance may degrade and it can take exponential time to complete.
D'Esopo-Pape Algorithm - O(e) Time and O(v + e) Space
This algorithm uses a Deque (or bi-directional queue) to efficiently manage the order in which vertices are processed for shortest path updates.
Initialize a distance array dist[] with all values set to infinity, except for the source vertex which is set to 0.
Construct the adjacency list from the given list of edges, where each vertex stores its neighbors along with the edge weights.
Maintain a boolean array inQueue[] to keep track of whether a vertex is already present in the queue, which prevents duplicate entries.
Append the source vertex to the queue and mark it as present in inQueue[].
While the queue is not empty, pop a vertex a from the front, mark it as not in the queue, and iterate through all of its adjacent vertices.
For each neighbor b of vertex a, check if the current distance to b is greater than the distance through a (i.e., dist[a] + weight). If yes, update dist[b].
After updating, check if b is not already in the queue using inQueue[]:
If b is being visited for the first time, append it to the back of the queue.
If b was visited before, append it to the front of the queue to prioritize its processing.
Once all vertices are processed, return the dist[] array which contains the shortest distance from the source to every vertex in the graph.
Illustration:
Initially, the Distance from source to itself will be 0 and for other vertices it will be infinite.
Now for each Adjacent vertex of source that is 0 in this case are [1, 4] update the distance and mark the vertices as present in the with weight of 4 and 8 respectively.
Now Dequeue the vertex 4 from the queue and following are the adjacent vertices are connected to the vertex 4 -
Vertex 1 - As Vertex 1 have already visited and the weight to reach the vertex 1 is 4, whereas when move to vertex 1 via the edge [4, 1] from source the total weight will be 11 which is greater than weight stored in the distance array.
Vertex 3 - As Vertex 3 is not visited and also not present in the queue, So the distance is updated to 9 for vertex 3 and also enqueued into the queue at the front.
Similarly Dequeue the vertex 3 from the Queue and update the values for adjacent vertex. Adjacent vertices of the vertex 3 is vertex 4 and vertex 2.
Vertex 4 - As vertex 4 is already visited and the weight is already minimum So Distance is not updated.
Vertex 2 - As Vertex 2 is not visited and also not present in the queue, So the distance is updated to 11 for vertex 3 and also enqueued into the queue at the front.
Below is the implementation of the above approach:
C++
// C++ code for finding single source shortest// path using D'Esopo-Pape Algorithm#include<bits/stdc++.h>usingnamespacestd;vector<int>dEsopoPape(intv,vector<vector<int>>&edges,intsrc){// Create adjacency list using 3D vectorvector<vector<vector<int>>>graph(v);for(auto&edge:edges){inta=edge[0];intb=edge[1];intw=edge[2];// Since undirected graph, add both directionsgraph[a].push_back({b,w});graph[b].push_back({a,w});}// Initialize dist array to infinityvector<int>dist(v,INT_MAX);dist[src]=0;// Queue to process verticesdeque<int>dq;// Boolean array to check if vertex is in queuevector<bool>inQueue(v,false);// Append source vertex to queuedq.push_back(src);inQueue[src]=true;// Process queue until emptywhile(!dq.empty()){// Pop vertex from frontinta=dq.front();dq.pop_front();inQueue[a]=false;// Explore all adjacent verticesfor(auto&nbr:graph[a]){intb=nbr[0];intw=nbr[1];// Relaxation conditionif(dist[b]>dist[a]+w){// Update distdist[b]=dist[a]+w;// Push b into queue if not already thereif(!inQueue[b]){inQueue[b]=true;// Decide position based on priorityif(dq.empty()||dist[b]>dist[dq.front()]){dq.push_back(b);}else{dq.push_front(b);}}}}}returndist;}// Driver codeintmain(){intv=5;vector<vector<int>>edges={{0,1,5},{1,2,1},{1,3,2},{2,4,1},{4,3,1}};intsrc=0;vector<int>res=dEsopoPape(v,edges,src);for(intx:res){cout<<x<<" ";}return0;}
Java
// Java code for finding single source shortest// path using D'Esopo-Pape Algorithmimportjava.util.*;classGfG{publicstaticint[]dEsopoPape(intv,int[][]edges,intsrc){// Create adjacency list using 3D vectorList<List<int[]>>graph=newArrayList<>();for(inti=0;i<v;i++){graph.add(newArrayList<>());}for(int[]edge:edges){inta=edge[0];intb=edge[1];intw=edge[2];// Since undirected graph, add both directionsgraph.get(a).add(newint[]{b,w});graph.get(b).add(newint[]{a,w});}// Initialize dist array to infinityint[]dist=newint[v];Arrays.fill(dist,Integer.MAX_VALUE);dist[src]=0;// Queue to process verticesDeque<Integer>dq=newArrayDeque<>();// Boolean array to check if vertex is in queueboolean[]inQueue=newboolean[v];// Append source vertex to queuedq.addLast(src);inQueue[src]=true;// Process queue until emptywhile(!dq.isEmpty()){// Pop vertex from frontinta=dq.pollFirst();inQueue[a]=false;// Explore all adjacent verticesfor(int[]nbr:graph.get(a)){intb=nbr[0];intw=nbr[1];// Relaxation conditionif(dist[b]>dist[a]+w){// Update distdist[b]=dist[a]+w;// Push b into queue if not already thereif(!inQueue[b]){inQueue[b]=true;// Decide position based on priorityif(dq.isEmpty()||dist[b]>dist[dq.peekFirst()]){dq.addLast(b);}else{dq.addFirst(b);}}}}}returndist;}publicstaticvoidmain(String[]args){intv=5;int[][]edges={{0,1,5},{1,2,1},{1,3,2},{2,4,1},{4,3,1}};intsrc=0;int[]res=dEsopoPape(v,edges,src);for(intx:res){System.out.print(x+" ");}}}
Python
# Python code for finding single source shortest# path using D'Esopo-Pape AlgorithmfromcollectionsimportdequedefdEsopoPape(v,edges,src):# Create adjacency list using 3D vectorgraph=[[]for_inrange(v)]foredgeinedges:a=edge[0]b=edge[1]w=edge[2]# Since undirected graph, add both directionsgraph[a].append([b,w])graph[b].append([a,w])# Initialize dist array to infinitydist=[float('inf')]*vdist[src]=0# Queue to process verticesdq=deque()# Boolean array to check if vertex is in queueinQueue=[False]*v# Append source vertex to queuedq.append(src)inQueue[src]=True# Process queue until emptywhiledq:# Pop vertex from fronta=dq.popleft()inQueue[a]=False# Explore all adjacent verticesfornbringraph[a]:b=nbr[0]w=nbr[1]# Relaxation conditionifdist[b]>dist[a]+w:# Update distdist[b]=dist[a]+w# Push b into queue if not already thereifnotinQueue[b]:inQueue[b]=True# Decide position based on priorityifnotdqordist[b]>dist[dq[0]]:dq.append(b)else:dq.appendleft(b)returndistif__name__=="__main__":v=5edges=[[0,1,5],[1,2,1],[1,3,2],[2,4,1],[4,3,1]]src=0res=dEsopoPape(v,edges,src)forxinres:print(x,end=" ")
C#
// C# code for finding single source shortest// path using D'Esopo-Pape AlgorithmusingSystem;usingSystem.Collections.Generic;classGfG{publicstaticint[]dEsopoPape(intv,int[][]edges,intsrc){// Create adjacency list using 3D vectorList<List<int[]>>graph=newList<List<int[]>>();for(inti=0;i<v;i++){graph.Add(newList<int[]>());}foreach(varedgeinedges){inta=edge[0];intb=edge[1];intw=edge[2];// Since undirected graph, add both directionsgraph[a].Add(newint[]{b,w});graph[b].Add(newint[]{a,w});}// Initialize dist array to infinityint[]dist=newint[v];for(inti=0;i<v;i++){dist[i]=int.MaxValue;}dist[src]=0;// Queue to process verticesLinkedList<int>dq=newLinkedList<int>();// Boolean array to check if vertex is in queuebool[]inQueue=newbool[v];// Append source vertex to queuedq.AddLast(src);inQueue[src]=true;// Process queue until emptywhile(dq.Count>0){// Pop vertex from frontinta=dq.First.Value;dq.RemoveFirst();inQueue[a]=false;// Explore all adjacent verticesforeach(varnbringraph[a]){intb=nbr[0];intw=nbr[1];// Relaxation conditionif(dist[b]>dist[a]+w){// Update distdist[b]=dist[a]+w;// Push b into queue if not already thereif(!inQueue[b]){inQueue[b]=true;// Decide position based on priorityif(dq.Count==0||dist[b]>dist[dq.First.Value]){dq.AddLast(b);}else{dq.AddFirst(b);}}}}}returndist;}publicstaticvoidMain(string[]args){intv=5;int[][]edges=newint[][]{newint[]{0,1,5},newint[]{1,2,1},newint[]{1,3,2},newint[]{2,4,1},newint[]{4,3,1}};intsrc=0;int[]res=dEsopoPape(v,edges,src);foreach(intxinres){Console.Write(x+" ");}}}
JavaScript
// Javascript code for finding single source shortest// path using D'Esopo-Pape AlgorithmfunctiondEsopoPape(v,edges,src){// Create adjacency list using 3D vectorletgraph=Array.from({length:v},()=>[]);for(letedgeofedges){leta=edge[0];letb=edge[1];letw=edge[2];// Since undirected graph, add both directionsgraph[a].push([b,w]);graph[b].push([a,w]);}// Initialize dist array to infinityletdist=newArray(v).fill(Infinity);dist[src]=0;// Queue to process verticesletdq=[];// Boolean array to check if vertex is in queueletinQueue=newArray(v).fill(false);// Append source vertex to queuedq.push(src);inQueue[src]=true;// Process queue until emptywhile(dq.length>0){// Pop vertex from frontleta=dq.shift();inQueue[a]=false;// Explore all adjacent verticesfor(letnbrofgraph[a]){letb=nbr[0];letw=nbr[1];// Relaxation conditionif(dist[b]>dist[a]+w){// Update distdist[b]=dist[a]+w;// Push b into queue if not already thereif(!inQueue[b]){inQueue[b]=true;// Decide position based on priorityif(dq.length===0||dist[b]>dist[dq[0]]){dq.push(b);}else{dq.unshift(b);}}}}}returndist;}// Driver Codeletv=5;letedges=[[0,1,5],[1,2,1],[1,3,2],[2,4,1],[4,3,1]];letsrc=0;letres=dEsopoPape(v,edges,src);for(letxofres){console.log(x+" ");}
Output
0 5 6 7 7
Time Complexity:O(e), where e is number of edges. Each edge is relaxed at most once; deque operations are constant time. Space Complexity:O(v + e), where v is number of vertices. Space used for distance array, inQueue array, and adjacency list.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.