Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph containsVvertices, numbered from 0 to V - 1.
Note: The given graph does not contain any negative edge.
Dijkstra’s Algorithm using Min Heap - O(E*logV) Time and O(V) Space
In Dijkstra's Algorithm, the goal is to find the shortest distance from a given source node to all other nodes in the graph. As the source node is the starting point, its distance is initialized to zero. From there, we iteratively pick the unprocessed node with the minimum distance from the source, this is where a min-heap (priority queue) or a set is typically used for efficiency. For each picked node u, we update the distance to its neighbors v using the formula: dist[v] = dist[u] + weight[u][v], but only if this new path offers a shorter distance than the current known one. This process continues until all nodes have been processed.
Step-by-Step Implementation
Set dist[source]=0 and all other distances as infinity.
Push the source node into the min heap as a pair <distance, node> → i.e., <0, source>.
Pop the top element (node with the smallest distance) from the min heap.
For each adjacent neighbor of the current node:
Calculate the distance using the formula: dist[v] = dist[u] + weight[u][v] If this new distance is shorter than the current dist[v], update it. Push the updated pair <dist[v], v> into the min heap
Repeat step 3 until the min heap is empty.
Return the distance array, which holds the shortest distance from the source to all nodes.
Illustration:
C++
//Driver Code Starts#include<iostream>#include<vector>#include<queue>#include<climits>usingnamespacestd;// Function to construct adjacency vector<vector<vector<int>>>constructAdj(vector<vector<int>>&edges,intV){// adj[u] = list of {v, wt}vector<vector<vector<int>>>adj(V);for(constauto&edge:edges){intu=edge[0];intv=edge[1];intwt=edge[2];adj[u].push_back({v,wt});adj[v].push_back({u,wt});}returnadj;}//Driver Code Ends// Returns shortest distances from src to all other verticesvector<int>dijkstra(intV,vector<vector<int>>&edges,intsrc){// Create adjacency listvector<vector<vector<int>>>adj=constructAdj(edges,V);// Create a priority queue to store vertices that// are being preprocessed.priority_queue<vector<int>,vector<vector<int>>,greater<vector<int>>>pq;// Create a vector for distances and initialize all// distances as infinitevector<int>dist(V,INT_MAX);// Insert source itself in priority queue and initialize// its distance as 0.pq.push({0,src});dist[src]=0;// Looping till priority queue becomes empty (or all// distances are not finalized) while(!pq.empty()){// The first vertex in pair is the minimum distance// vertex, extract it from priority queue.intu=pq.top()[1];pq.pop();// Get all adjacent of u.for(autox:adj[u]){// Get vertex label and weight of current// adjacent of u.intv=x[0];intweight=x[1];// If there is shorter path to v through u.if(dist[v]>dist[u]+weight){// Updating distance of vdist[v]=dist[u]+weight;pq.push({dist[v],v});}}}returndist;}//Driver Code Starts// Driver program to test methods of graph classintmain(){intV=5;intsrc=0;// edge list format: {u, v, weight}vector<vector<int>>edges={{0,1,4},{0,2,8},{1,4,6},{2,3,2},{3,4,10}};vector<int>result=dijkstra(V,edges,src);// Print shortest distances in one linefor(intdist:result)cout<<dist<<" ";return0;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.*;classGfG{// Construct adjacency list using ArrayList of ArrayListstaticArrayList<ArrayList<ArrayList<Integer>>>constructAdj(int[][]edges,intV){// Initialize the adjacency listArrayList<ArrayList<ArrayList<Integer>>>adj=newArrayList<>();for(inti=0;i<V;i++){adj.add(newArrayList<>());}// Fill the adjacency list from edgesfor(int[]edge:edges){intu=edge[0];intv=edge[1];intwt=edge[2];// Add edge from u to vArrayList<Integer>e1=newArrayList<>();e1.add(v);e1.add(wt);adj.get(u).add(e1);// Since the graph is undirected, add edge from v to uArrayList<Integer>e2=newArrayList<>();e2.add(u);e2.add(wt);adj.get(v).add(e2);}returnadj;}//Driver Code Ends// Returns shortest distances from src to all other verticesstaticint[]dijkstra(intV,int[][]edges,intsrc){// Create adjacency listArrayList<ArrayList<ArrayList<Integer>>>adj=constructAdj(edges,V);// PriorityQueue to store vertices to be processed// Each element is a pair: [distance, node]PriorityQueue<ArrayList<Integer>>pq=newPriorityQueue<>(Comparator.comparingInt(a->a.get(0)));// Create a distance array and initialize all distances as infiniteint[]dist=newint[V];Arrays.fill(dist,Integer.MAX_VALUE);// Insert source with distance 0dist[src]=0;ArrayList<Integer>start=newArrayList<>();start.add(0);start.add(src);pq.offer(start);// Loop until the priority queue is emptywhile(!pq.isEmpty()){// Get the node with the minimum distanceArrayList<Integer>curr=pq.poll();intd=curr.get(0);intu=curr.get(1);// Traverse all adjacent vertices of the current nodefor(ArrayList<Integer>neighbor:adj.get(u)){intv=neighbor.get(0);intweight=neighbor.get(1);// If there is a shorter path to v through uif(dist[v]>dist[u]+weight){// Update distance of vdist[v]=dist[u]+weight;// Add updated pair to the queueArrayList<Integer>temp=newArrayList<>();temp.add(dist[v]);temp.add(v);pq.offer(temp);}}}// Return the shortest distance arrayreturndist;}//Driver Code Starts// Driver program to test methods of graph classpublicstaticvoidmain(String[]args){intV=5;intsrc=0;// Edge list format: {u, v, weight}int[][]edges={{0,1,4},{0,2,8},{1,4,6},{2,3,2},{3,4,10}};// Get shortest path distancesint[]result=dijkstra(V,edges,src);// Print shortest distances in one linefor(intd:result)System.out.print(d+" ");}}//Driver Code Ends
Python
#Driver Code Startsimportheapqimportsys# Function to construct adjacency defconstructAdj(edges,V):# adj[u] = list of [v, wt]adj=[[]for_inrange(V)]foredgeinedges:u,v,wt=edgeadj[u].append([v,wt])adj[v].append([u,wt])returnadj#Driver Code Ends# Returns shortest distances from src to all other verticesdefdijkstra(V,edges,src):# Create adjacency listadj=constructAdj(edges,V)# Create a priority queue to store vertices that# are being preprocessed.pq=[]# Create a list for distances and initialize all# distances as infinitedist=[sys.maxsize]*V# Insert source itself in priority queue and initialize# its distance as 0.heapq.heappush(pq,[0,src])dist[src]=0# Looping till priority queue becomes empty (or all# distances are not finalized) whilepq:# The first vertex in pair is the minimum distance# vertex, extract it from priority queue.u=heapq.heappop(pq)[1]# Get all adjacent of u.forxinadj[u]:# Get vertex label and weight of current# adjacent of u.v,weight=x[0],x[1]# If there is shorter path to v through u.ifdist[v]>dist[u]+weight:# Updating distance of vdist[v]=dist[u]+weightheapq.heappush(pq,[dist[v],v])# Return the shortest distance arrayreturndist#Driver Code Starts# Driver program to test methods of graph classif__name__=="__main__":V=5src=0# edge list format: {u, v, weight}edges=[[0,1,4],[0,2,8],[1,4,6],[2,3,2],[3,4,10]];result=dijkstra(V,edges,src)# Print shortest distances in one lineprint(' '.join(map(str,result)))#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;classGfG{// MinHeap Node (stores vertex and its distance)classHeapNode{publicintVertex;publicintDistance;publicHeapNode(intv,intd){Vertex=v;Distance=d;}}// Custom MinHeap classclassMinHeap{privateList<HeapNode>heap=newList<HeapNode>();publicintCount=>heap.Count;privatevoidSwap(inti,intj){vartemp=heap[i];heap[i]=heap[j];heap[j]=temp;}publicvoidPush(HeapNodenode){heap.Add(node);inti=heap.Count-1;while(i>0){intparent=(i-1)/2;if(heap[parent].Distance<=heap[i].Distance)break;Swap(i,parent);i=parent;}}publicHeapNodePop(){if(heap.Count==0)returnnull;varroot=heap[0];heap[0]=heap[heap.Count-1];heap.RemoveAt(heap.Count-1);Heapify(0);returnroot;}privatevoidHeapify(inti){intsmallest=i;intleft=2*i+1;intright=2*i+2;if(left<heap.Count&&heap[left].Distance<heap[smallest].Distance)smallest=left;if(right<heap.Count&&heap[right].Distance<heap[smallest].Distance)smallest=right;if(smallest!=i){Swap(i,smallest);Heapify(smallest);}}}// Build adjacency list from edge liststaticList<int[]>[]constructAdj(int[,]edges,intV){List<int[]>[]adj=newList<int[]>[V];for(inti=0;i<V;i++)adj[i]=newList<int[]>();intE=edges.GetLength(0);for(inti=0;i<E;i++){intu=edges[i,0];intv=edges[i,1];intwt=edges[i,2];adj[u].Add(newint[]{v,wt});adj[v].Add(newint[]{u,wt});// Undirected graph}returnadj;}//Driver Code Ends// Dijkstra's algorithm using custom MinHeapstaticint[]dijkstra(intV,int[,]edges,intsrc){varadj=constructAdj(edges,V);int[]dist=newint[V];bool[]visited=newbool[V];for(inti=0;i<V;i++)dist[i]=int.MaxValue;dist[src]=0;MinHeappq=newMinHeap();pq.Push(newHeapNode(src,0));while(pq.Count>0){HeapNodenode=pq.Pop();intu=node.Vertex;if(visited[u])continue;visited[u]=true;foreach(varneighborinadj[u]){intv=neighbor[0];intweight=neighbor[1];if(!visited[v]&&dist[u]+weight<dist[v]){dist[v]=dist[u]+weight;pq.Push(newHeapNode(v,dist[v]));}}}returndist;}//Driver Code Starts// Main methodstaticvoidMain(string[]args){intV=5;intsrc=0;int[,]edges={{0,1,4},{0,2,8},{1,4,6},{2,3,2},{3,4,10}};int[]result=dijkstra(V,edges,src);foreach(intdinresult)Console.Write(d+" ");}}//Driver Code Ends
JavaScript
//Driver Code StartsclassMinHeap{constructor(){this.heap=[];}push(val){this.heap.push(val);this._heapifyUp(this.heap.length-1);}pop(){if(this.size()===0)returnnull;if(this.size()===1)returnthis.heap.pop();constmin=this.heap[0];this.heap[0]=this.heap.pop();this._heapifyDown(0);returnmin;}size(){returnthis.heap.length;}_heapifyUp(index){while(index>0){constparent=Math.floor((index-1)/2);if(this.heap[parent][0]<=this.heap[index][0])break;[this.heap[parent],this.heap[index]]=[this.heap[index],this.heap[parent]];index=parent;}}_heapifyDown(index){constn=this.heap.length;while(true){letsmallest=index;constleft=2*index+1;constright=2*index+2;if(left<n&&this.heap[left][0]<this.heap[smallest][0]){smallest=left;}if(right<n&&this.heap[right][0]<this.heap[smallest][0]){smallest=right;}if(smallest===index)break;[this.heap[smallest],this.heap[index]]=[this.heap[index],this.heap[smallest]];index=smallest;}}}// Function to construct adjacency functionconstructAdj(edges,V){// adj[u] = list of [v, wt]constadj=Array.from({length:V},()=>[]);for(constedgeofedges){const[u,v,wt]=edge;adj[u].push([v,wt]);adj[v].push([u,wt]);}returnadj;}//Driver Code Ends// Returns shortest distances from src to all other verticesfunctiondijkstra(V,edges,src){// Create adjacency listconstadj=constructAdj(edges,V);// Create a min heap to store <distance, node>constminHeap=newMinHeap();// Create an array for distances and initialize all distances as infinityconstdist=Array(V).fill(Number.MAX_SAFE_INTEGER);// Push the source node with distance 0minHeap.push([0,src]);dist[src]=0;// Process the heapwhile(minHeap.size()>0){const[d,u]=minHeap.pop();// Traverse all adjacent of ufor(const[v,weight]ofadj[u]){if(dist[v]>dist[u]+weight){dist[v]=dist[u]+weight;minHeap.push([dist[v],v]);}}}returndist;}//Driver Code Starts// Driver codeconstV=5;constsrc=0;// edge list format: [u, v, weight]constedges=[[0,1,4],[0,2,8],[1,4,6],[2,3,2],[3,4,10]];constresult=dijkstra(V,edges,src);// Print shortest distances in one lineconsole.log(result.join(' '));//Driver Code Ends
Output
0 4 8 10 10
Time Complexity: O(E*logV), Where E is the number of edges and V is the number of vertices. Auxiliary Space: O(V), Where V is the number of vertices, We do not count the adjacency list in auxiliary space as it is necessary for representing the input graph.
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.