VOOZH about

URL: https://www.geeksforgeeks.org/dsa/shortest-path-faster-algorithm/

⇱ Shortest Path Faster Algorithm - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Shortest Path Faster Algorithm

Last Updated : 12 Jul, 2025

Prerequisites: Bellman-Ford Algorithm
Given a directed weighted graph with V vertices, E edges and a source vertex S. The task is to find the shortest path from the source vertex to all other vertices in the given graph.
Example: 
 

Input: V = 5, S = 1, arr = {{1, 2, 1}, {2, 3, 7}, {2, 4, -2}, {1, 3, 8}, {1, 4, 9}, {3, 4, 3}, {2, 5, 3}, {4, 5, -3}} 
Output: 
1, 0 
2, 1 
3, 8 
4, -1 
5, -4 
Explanation: For the given input, the shortest path from 1 to 1 is 0, 1 to 2 is 1 and so on.
Input: V = 5, S = 1, arr = {{1, 2, -1}, {1, 3, 4}, {2, 3, 3}, {2, 4, 2}, {2, 5, 2}, {4, 3, 5}, {4, 2, 1}, {5, 4, 3}} 
Output: 
1, 0 
2, -1 
3, 2 
4, 1 
5, 1 
 


 


Approach: The shortest path faster algorithm is based on Bellman-Ford algorithm where every vertex is used to relax its adjacent vertices but in SPF algorithm, a queue of vertices is maintained and a vertex is added to the queue only if that vertex is relaxed. This process repeats until no more vertex can be relaxed. 
The following steps can be performed to compute the result: 
 

  1. Create an array d[] to store the shortest distance of all vertex from the source vertex. Initialize this array by infinity except for d[S] = 0 where S is the source vertex.
  2. Create a queue Q and push starting source vertex in it. 
    • while Queue is not empty, do the following for each edge(u, v) in the graph 
      • If d[v] > d[u] + weight of edge(u, v)
      • d[v] = d[u] + weight of edge(u, v)
      • If vertex v is not present in Queue, then push the vertex v into the Queue.


Note: The term relaxation means updating the cost of all vertices connected to a vertex v if those costs would be improved by including the path via vertex v. This can be understood better from an analogy between the estimate of the shortest path and the length of a helical tension spring, which is not designed for compression. Initially, the cost of the shortest path is an overestimate, likened to a stretched-out spring. As shorter paths are found, the estimated cost is lowered, and the spring is relaxed. Eventually, the shortest path, if one exists, is found and the spring has been relaxed to its resting length.
Below is the implementation of the above approach: 
 


Output: 
Vertex Distance from source
1 0
2 1
3 8
4 -1
5 -4

 

Time Complexity: 
Average Time Complexity: O(|E|) 
Worstcase Time Complexity: O(|V|.|E|) 

Space complexity: O(V),The space complexity is O(V) since we need to store the distances for each vertex in an array.


Note: Bound on average runtime has not been proved yet.
References: Shortest Path Faster Algorithm
 

Comment
Article Tags:
Article Tags: