Dijkstra's Algorithm Part 2
Dijkstra’s Algorithm finds shortest paths from a src
node to all the vertices of the graph. However it does not work for the graphs having negative weight edges. The benefit of Dijsktra’s algorithm
is that it is more efficient and can be used for processing large graphs.
Note: The below implementation is optimal for sparse graphs.
Time Complexity: O(n + mlogm)
where n
: number of vertices and m
: number of edges
In part-1, the time required to find the vertex with the least distance value and not already in the processed set, is of the order of O(n) contributing to O(n2) part of the complexity.
In this implementation, I am going to show how priority queue data structure can be used instead of an array to yield the same functionality but with a better time complexity.
Pseudo code for Dijsktra’s Algorithm (for Sparse graphs):
Note: Negative value of distance is pushed to the priority queue because we want the minimum distance vertex to be at the top but the default version of C++ priority queue keeps maximum element at the top.
References: cp-algorithms