How to Implement Dijkstra’s Shortest Path Algorithm in Python

In this tutorial, we will learn how to implement Dijkstra’s Shortest Path Algorithm in Python. The main objective is to understand its implementation clearly and effectively. This guide will walk you step by step through the process, making it easier to follow and apply. By the end of this tutorial, you will have a solid understanding of how Dijkstra’s Shortest Path Algorithm works in Python, helping you strengthen your problem-solving abilities and improve your overall coding skills in data structure implementation.

This topic is straightforward and easy to understand. By following the instructions provided, you will be able to complete it with ease. The tutorial will guide you step by step through the process of implementing Dijkstra’s Shortest Path Algorithm. So, let’s dive into the coding process and start implementing the solution to gain a deeper understanding of graph algorithms in Python

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. class Graph:
  2.     def __init__(self):
  3.         self.vertices = {}
  4.  
  5.     def add_vertex(self, key):
  6.         vertex = Vertex(key)
  7.         self.vertices[key] = vertex
  8.  
  9.     def get_vertex(self, key):
  10.         return self.vertices[key]
  11.  
  12.     def __contains__(self, key):
  13.         return key in self.vertices
  14.  
  15.     def add_edge(self, src_key, dest_key, weight=1):
  16.         self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
  17.  
  18.     def does_edge_exist(self, src_key, dest_key):
  19.         return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
  20.  
  21.     def __iter__(self):
  22.         return iter(self.vertices.values())
  23.  
  24.  
  25. class Vertex:
  26.     def __init__(self, key):
  27.         self.key = key
  28.         self.points_to = {}
  29.  
  30.     def get_key(self):
  31.         return self.key
  32.  
  33.     def add_neighbour(self, dest, weight):
  34.         self.points_to[dest] = weight
  35.  
  36.     def get_neighbours(self):
  37.         return self.points_to.keys()
  38.  
  39.     def get_weight(self, dest):
  40.         return self.points_to[dest]
  41.  
  42.     def does_it_point_to(self, dest):
  43.         return dest in self.points_to
  44.  
  45.  
  46. def dijkstra(g, source):
  47.     unvisited = set(g)
  48.     distance = dict.fromkeys(g, float('inf'))
  49.     distance[source] = 0
  50.  
  51.     while unvisited:
  52.         closest = min(unvisited, key=lambda v: distance[v])
  53.         unvisited.remove(closest)
  54.  
  55.         for neighbour in closest.get_neighbours():
  56.             if neighbour in unvisited:
  57.                 new_distance = distance[closest] + closest.get_weight(neighbour)
  58.                 if distance[neighbour] > new_distance:
  59.                     distance[neighbour] = new_distance
  60.  
  61.     return distance
  62.  
  63.  
  64. # MAIN PROGRAM
  65. g = Graph()
  66.  
  67. while True:
  68.     print("\n===== Dijkstra’s Shortest Path Algorithm =====")
  69.     print("Undirected Graph")
  70.     print("Menu")
  71.     print("add vertex <key>")
  72.     print("add edge <src> <dest> <weight>")
  73.     print("shortest <source vertex key>")
  74.     print("display")
  75.     print("quit")
  76.  
  77.     do = input('What would you like to do? ').split()
  78.  
  79.     if not do:
  80.         continue
  81.  
  82.     operation = do[0]
  83.  
  84.     if operation == 'add':
  85.         suboperation = do[1]
  86.  
  87.         if suboperation == 'vertex':
  88.             key = int(do[2])
  89.             if key not in g:
  90.                 g.add_vertex(key)
  91.             else:
  92.                 print('Vertex already exists.')
  93.  
  94.         elif suboperation == 'edge':
  95.             src = int(do[2])
  96.             dest = int(do[3])
  97.             weight = int(do[4])
  98.  
  99.             if src not in g:
  100.                 print(f'Vertex {src} does not exist.')
  101.             elif dest not in g:
  102.                 print(f'Vertex {dest} does not exist.')
  103.             else:
  104.                 if not g.does_edge_exist(src, dest):
  105.                     g.add_edge(src, dest, weight)
  106.                     g.add_edge(dest, src, weight)
  107.                 else:
  108.                     print('Edge already exists.')
  109.  
  110.     elif operation == 'shortest':
  111.         key = int(do[1])
  112.         source = g.get_vertex(key)
  113.         distance = dijkstra(g, source)
  114.  
  115.         print(f'Distances from {key}:')
  116.         for v in distance:
  117.             print(f'Distance to {v.get_key()}: {distance[v]}')
  118.  
  119.     elif operation == 'display':
  120.         print('Vertices:', end=' ')
  121.         for v in g:
  122.             print(v.get_key(), end=' ')
  123.         print()
  124.  
  125.         print('Edges:')
  126.         for v in g:
  127.             for dest in v.get_neighbours():
  128.                 w = v.get_weight(dest)
  129.                 print(f'(src={v.get_key()}, dest={dest.get_key()}, weight={w})')
  130.  
  131.     elif operation == 'quit':
  132.         print("Exiting program...")
  133.         break
  134.  
  135.     else:
  136.         print("Invalid command.")

This Python program allows users to create and interact with an undirected, weighted graph, supporting vertex and edge additions, graph display, and shortest path calculation using Dijkstra’s algorithm. It defines `Graph` and `Vertex` classes to manage vertices and their connections, while a command-line menu enables easy input and ensures validation, preventing duplicates and maintaining undirected edges.

Output:

There you have it we successfully created How to Implement Dijkstra’s Shortest Path Algorithm in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials