Dijkstra's Algorithm in Python

Find the shortest routes between a source vertex and each vertex in the provided graph, given the graph and the source vertex.

Dijkstra's method and Prim's approach for the minimal spanning tree are extremely similar. We create an SPT (shortest path tree) with a specified source as the root, similar to Prim's MST. We keep two sets; one set has vertices that are part of the shortest-path tree, while the other set contains vertices that aren't yet a part of the tree. We look for a vertex in the other set (the set still needs to be included) with a minimal distance from the source at each stage of the method.

The exact steps taken by Dijkstra's method to determine the shortest route between a single source vertex and every other vertex in the supplied graph are listed below.

Algorithm:

  1. Create a set called sptSet (shortest path tree set) using algorithm 1 to keep track of the vertices that are part of the shortest path tree, whose minimal distance from the source is determined and determined. This collection is initially empty.
  2. Give each vertex in the input network a distance value. Set all distance values to INFINITE at the beginning. Set the source vertex's distance value to 0 to ensure it is chosen first.
  3. Even if sptSet is missing certain vertices:
    • Choose a vertex u with a minimum distance value not present in the sptSet.
    • Add you to the sptSet.
    • Update the distance between each of its neighboring vertices. Iterate over all nearby vertices to update the distance values. If the weight of the edge u-v plus the distance value of u (from source) for each neighboring vertex v is less than the distance value of v, then the distance value of v should be updated.

Program Code:

Output:

Vertex      Distance from Source
0          0
1          4
2          12
3          19
4          21
5          11
6          9
7          8
8          14
  • Time Complexity: The Dijkstra algorithm has an O(V2) time complexity. This is due to the algorithm's using two nested loops to iteratively search the network for the shortest route connecting all nodes to the source node.
  • Space Complexity: Dijkstra's algorithm has an O(V) space complexity, where V is the number of vertices in the graph. This is so that the method may record the distances between the source node and every other node in an array of size V.