How to Implement Floyd-Warshall Algorithm in Python

In this tutorial, we will learn "How to Implement the Floyd–Warshall Algorithm in Python". The main objective is to understand and implement the algorithm effectively. This guide will walk you step by step through the process, making it easy to follow and apply. By the end of this tutorial, you will have a solid understanding of how the Floyd–Warshall 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 program will guide you step by step through the process of implementing the Bellman-Ford Algorithm. So, let’s dive into the coding process and start implementing the solution to gain a deeper understanding of Python programming.

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 __len__(self):
  22.         return len(self.vertices)
  23.  
  24.     def __iter__(self):
  25.         return iter(self.vertices.values())
  26.  
  27.  
  28. class Vertex:
  29.     def __init__(self, key):
  30.         self.key = key
  31.         self.points_to = {}
  32.  
  33.     def get_key(self):
  34.         return self.key
  35.  
  36.     def add_neighbour(self, dest, weight):
  37.         self.points_to[dest] = weight
  38.  
  39.     def get_neighbours(self):
  40.         return self.points_to.keys()
  41.  
  42.     def get_weight(self, dest):
  43.         return self.points_to[dest]
  44.  
  45.     def does_it_point_to(self, dest):
  46.         return dest in self.points_to
  47.  
  48.  
  49. def floyd_warshall(g):
  50.     distance = {v: dict.fromkeys(g, float('inf')) for v in g}
  51.     next_v = {v: dict.fromkeys(g, None) for v in g}
  52.  
  53.     for v in g:
  54.         for n in v.get_neighbours():
  55.             distance[v][n] = v.get_weight(n)
  56.             next_v[v][n] = n
  57.  
  58.     for v in g:
  59.         distance[v][v] = 0
  60.  
  61.     for p in g:
  62.         for v in g:
  63.             for w in g:
  64.                 if distance[v][w] > distance[v][p] + distance[p][w]:
  65.                     distance[v][w] = distance[v][p] + distance[p][w]
  66.                     next_v[v][w] = next_v[v][p]
  67.  
  68.     return distance, next_v
  69.  
  70.  
  71. def print_path(next_v, u, v):
  72.     if next_v[u][v] is None:
  73.         print("No path", end='')
  74.         return
  75.  
  76.     p = u
  77.     while p != v:
  78.         print(f"{p.get_key()} -> ", end='')
  79.         p = next_v[p][v]
  80.     print(v.get_key(), end='')
  81.  
  82.  
  83. # MAIN PROGRAM
  84. g = Graph()
  85.  
  86. while True:
  87.     print("\n===== Floyd-Warshall Algorithm =====")
  88.     print("Menu")
  89.     print("add vertex <key>")
  90.     print("add edge <src> <dest> <weight>")
  91.     print("floyd-warshall")
  92.     print("display")
  93.     print("quit")
  94.  
  95.     do = input('What would you like to do? ').split()
  96.     if not do:
  97.         continue
  98.  
  99.     operation = do[0]
  100.  
  101.     if operation == 'add':
  102.         suboperation = do[1]
  103.  
  104.         if suboperation == 'vertex':
  105.             key = int(do[2])
  106.             if key not in g:
  107.                 g.add_vertex(key)
  108.             else:
  109.                 print('Vertex already exists.')
  110.  
  111.         elif suboperation == 'edge':
  112.             src = int(do[2])
  113.             dest = int(do[3])
  114.             weight = int(do[4])
  115.  
  116.             if src not in g:
  117.                 print(f'Vertex {src} does not exist.')
  118.             elif dest not in g:
  119.                 print(f'Vertex {dest} does not exist.')
  120.             else:
  121.                 if not g.does_edge_exist(src, dest):
  122.                     g.add_edge(src, dest, weight)
  123.                 else:
  124.                     print('Edge already exists.')
  125.  
  126.     elif operation == 'floyd-warshall':
  127.         distance, next_v = floyd_warshall(g)
  128.         print("\nShortest paths:")
  129.         for start in g:
  130.             for end in g:
  131.                 if start != end and distance[start][end] != float('inf'):
  132.                     print(f'From {start.get_key()} to {end.get_key()}: ', end='')
  133.                     print_path(next_v, start, end)
  134.                     print(f' (distance {distance[start][end]})')
  135.  
  136.     elif operation == 'display':
  137.         print('Vertices:', end=' ')
  138.         for v in g:
  139.             print(v.get_key(), end=' ')
  140.         print()
  141.  
  142.         print('Edges:')
  143.         for v in g:
  144.             for dest in v.get_neighbours():
  145.                 w = v.get_weight(dest)
  146.                 print(f'(src={v.get_key()}, dest={dest.get_key()}, weight={w})')
  147.  
  148.     elif operation == 'quit':
  149.         print("Exiting program...")
  150.         break
  151.  
  152.     else:
  153.         print("Invalid command.")
  154.  
  155.     # Try Again Option
  156.     opt = input("\nDo you want to continue? (yes/no): ").strip().lower()
  157.     if opt == "no":
  158.         print("Exiting program...")
  159.         break
  160.     elif opt != "yes":
  161.         print("Invalid choice. Exiting program...")
  162.         break

This Python program provides an interactive implementation of the Floyd-Warshall algorithm for finding shortest paths between all pairs of vertices in a weighted graph. It defines `Graph` and `Vertex` classes to manage the graph structure, where vertices store their neighboring connections and edge weights. The `floyd_warshall` function computes the shortest distances between every pair of vertices and also tracks the path using a helper structure, allowing reconstruction of the actual routes. A `print_path` function is used to display these shortest paths clearly. Through a command-line menu, users can add vertices and edges, display the graph, run the algorithm to view all shortest paths and distances, and exit the program, with input validation to ensure proper graph construction.

Output:

There you have it we successfully created How to Implement Floyd-Warshall 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