{"id":62047,"date":"2024-04-30T08:31:11","date_gmt":"2024-04-30T08:31:11","guid":{"rendered":"https:\/\/www.askpython.com\/?p=62047"},"modified":"2025-04-10T20:29:35","modified_gmt":"2025-04-10T20:29:35","slug":"floyd-warshall-algorithm-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/floyd-warshall-algorithm-python","title":{"rendered":"Floyd-Warshall Algorithm in Python: Shortest Path Between Cities"},"content":{"rendered":"\n<p>The Floyd-Warshall algorithm is a renowned technique for finding the shortest paths between all pairs of nodes in a weighted graph or network. We can solve complex routing problems and optimize various processes by using this algorithm. In this article, we&#8217;ll explore the underlying principles of the Floyd-Warshall algorithm and its implementation in Python, along with a practical case study illustrating its application in finding the shortest routes between Indian cities.<\/p>\n\n\n\n<p><strong><em>Recommended: <a href=\"https:\/\/www.askpython.com\/resources\/connected-health-exploring-iot-solutions-for-healthcare-transformation\">Connected Health: Exploring IoT Solutions for Healthcare Transformation<\/a><\/em><\/strong><\/p>\n\n\n\n<p><strong><em>Recommended: <a href=\"https:\/\/www.askpython.com\/python\/examples\/levenshtein-python-troubleshooting-install\">Levenshtein Distance in Python: Troubleshooting Installation Errors on Windows<\/a><\/em><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Understanding the Floyd-Warshall Algorithm<\/h2>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><em>The Floyd-Warshall algorithm is a dynamic programming approach that finds the shortest paths between all pairs of vertices in a weighted graph. It operates by iteratively updating a distance matrix, considering all possible intermediate vertices. The algorithm has a time complexity of O(n^3), where n is the number of vertices, making it efficient for solving the all-pairs shortest path problem.<\/em><\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\">Implementing the Floyd-Warshall Algorithm in Python<\/h2>\n\n\n\n<p>The Python implementation of the Floyd-Warshall algorithm utilizes nested loops to iterate through all possible vertices and update the distance matrix accordingly. <\/p>\n\n\n\n<p>The key steps involve initializing the distance matrix with the given edge weights, then iterating through each vertex as a potential intermediate node, updating the distance matrix if a shorter path is found. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Number of vertices in the graph\nV = 4\n\n# Define infinity as a large enough value. This value will be used\n# for vertices not connected to each other\nINF = 99999\n\n# Solves all pair shortest path via Floyd Warshall Algorithm\ndef floydWarshall(graph):\n    &quot;&quot;&quot; dist&#x5B;]&#x5B;] will be the output matrix that will finally have the shortest\n    distances between every pair of vertices &quot;&quot;&quot;\n    &quot;&quot;&quot; initializing the solution matrix same as input graph matrix\n    OR we can say that the initial values of shortest distances\n    are based on shortest paths considering no intermediate vertex &quot;&quot;&quot;\n    dist = list(map(lambda i: list(map(lambda j: j, i)), graph))\n    \n    &quot;&quot;&quot; Add all vertices one by one to the set of intermediate\n    vertices.\n    ---&gt; Before start of an iteration, we have shortest distances\n    between all pairs of vertices such that the shortest\n    distances consider only the vertices in the set\n    {0, 1, 2, .. k-1} as intermediate vertices.\n    ----&gt; After the end of an iteration, vertex no. k is added\n    to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} &quot;&quot;&quot;\n    for k in range(V):\n \n        # pick all vertices as source one by one\n        for i in range(V):\n \n            # Pick all vertices as destination for the\n            # above picked source\n            for j in range(V):\n \n                # If vertex k is on the shortest path from\n                # i to j, then update the value of dist&#x5B;i]&#x5B;j]\n                dist&#x5B;i]&#x5B;j] = min(dist&#x5B;i]&#x5B;j], dist&#x5B;i]&#x5B;k] + dist&#x5B;k]&#x5B;j])\n    printSolution(dist)\n    plotGraph(graph, dist)\n\n# A utility function to print the solution\ndef printSolution(dist):\n    print(&quot;Following matrix shows the shortest distances between every pair of vertices&quot;)\n    for i in range(V):\n        for j in range(V):\n            if(dist&#x5B;i]&#x5B;j] == INF):\n                print(&quot;%7s&quot; % (&quot;INF&quot;), end=&quot; &quot;)\n            else:\n                print(&quot;%7d\\t&quot; % (dist&#x5B;i]&#x5B;j]), end=&quot; &quot;)\n            if j == V-1:\n                print(&quot;&quot;)\n\n# A utility function to plot the graph and highlight the shortest paths\ndef plotGraph(graph, dist):\n    plt.figure(figsize=(8, 6))\n    G = np.array(graph)\n    np.fill_diagonal(G, 0)\n    plt.imshow(G, cmap=&#039;Greys&#039;, interpolation=&#039;nearest&#039;)\n    for i in range(V):\n        for j in range(V):\n            if dist&#x5B;i]&#x5B;j] != graph&#x5B;i]&#x5B;j] and graph&#x5B;i]&#x5B;j] != INF:\n                plt.text(j, i, str(graph&#x5B;i]&#x5B;j]), horizontalalignment=&#039;center&#039;, verticalalignment=&#039;center&#039;, fontdict={&#039;color&#039;:&#039;red&#039;})\n            if dist&#x5B;i]&#x5B;j] != INF:\n                plt.text(j, i, str(dist&#x5B;i]&#x5B;j]), horizontalalignment=&#039;center&#039;, verticalalignment=&#039;center&#039;, fontdict={&#039;color&#039;:&#039;blue&#039;})\n    plt.title(&quot;Graph with Shortest Paths (Red: Original, Blue: Shortest)&quot;)\n    plt.xlabel(&quot;Vertices&quot;)\n    plt.ylabel(&quot;Vertices&quot;)\n    plt.xticks(np.arange(V))\n    plt.yticks(np.arange(V))\n    plt.gca().invert_yaxis()\n    plt.colorbar(label=&quot;Edge Weight&quot;)\n    plt.grid(True, linestyle=&#039;--&#039;, linewidth=0.5)\n    plt.show()\n\n# Driver program to test the above program\n# Let us create the following weighted graph\n&quot;&quot;&quot;\n             10\n        (0)-------&gt;(3)\n         |         \/|\\\n       5 |          |\n         |          | 1\n        \\|\/         |\n        (1)-------&gt;(2)\n             3           &quot;&quot;&quot;\ngraph = &#x5B;&#x5B;0, 5, INF, 10],\n         &#x5B;INF, 0, 3, INF],\n         &#x5B;INF, INF, 0,   1],\n         &#x5B;INF, INF, INF, 0]\n        ]\n# Print the solution and plot the graph\nfloydWarshall(graph)\n\n<\/pre><\/div>\n\n\n<p>The solution is visualized using the matplotlib library, highlighting the original and shortest path weights. Let us look at the output for the same.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"647\" height=\"547\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Floyd-Warshall-Output.png\" alt=\"Floyd Warshall Output\" class=\"wp-image-62060\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Floyd-Warshall-Output.png 647w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Floyd-Warshall-Output-300x254.png 300w\" sizes=\"auto, (max-width: 647px) 100vw, 647px\" \/><figcaption class=\"wp-element-caption\"><strong><em>Floyd Warshall Output<\/em><\/strong><\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Case Study: Finding Shortest Paths Between Indian Cities<\/h2>\n\n\n\n<p>Let us now consider a case where we need to find the shortest distance between cities. We have three cities which are Mumbai, Delhi, and Bangalore.<\/p>\n\n\n\n<p>Let&#8217;s assume that-<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Mumbai is connected to Delhi with a distance of 10 units.<\/li>\n\n\n\n<li>Mumbai is connected to Bangalore with a distance of 15 units.<\/li>\n\n\n\n<li>Bangalore is connected to Delhi with a distance of 5 units.<\/li>\n<\/ol>\n\n\n\n<p>We need to find the shortest distance. Let us look at the code.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Number of cities in the network\nnum_cities = 3\n\n# Define infinity as a large enough value. This value will be used\n# for cities not connected to each other\nINF = 99999\n\n# Function to find the shortest paths between all pairs of cities\ndef find_shortest_paths(distances):\n    &quot;&quot;&quot; dist&#x5B;]&#x5B;] will be the output matrix that will finally have the shortest\n    distances between every pair of cities &quot;&quot;&quot;\n    &quot;&quot;&quot; initializing the solution matrix same as input distances matrix\n    OR we can say that the initial values of shortest distances\n    are based on shortest paths considering no intermediate city &quot;&quot;&quot;\n    dist = np.copy(distances)\n    \n    &quot;&quot;&quot; Add all cities one by one to the set of intermediate\n    cities.\n    ---&gt; Before start of an iteration, we have shortest distances\n    between all pairs of cities such that the shortest\n    distances consider only the cities in the set\n    {0, 1, 2, .. k-1} as intermediate cities.\n    ----&gt; After the end of an iteration, city no. k is added\n    to the set of intermediate cities and the set becomes {0, 1, 2, .. k} &quot;&quot;&quot;\n    for k in range(num_cities):\n        for i in range(num_cities):\n            for j in range(num_cities):\n                # If city k is on the shortest path from\n                # city i to city j, then update the value of dist&#x5B;i]&#x5B;j]\n                dist&#x5B;i]&#x5B;j] = min(dist&#x5B;i]&#x5B;j], dist&#x5B;i]&#x5B;k] + dist&#x5B;k]&#x5B;j])\n    return dist\n\n# Function to plot the network of cities and roads\ndef plot_city_network(distances, city_names):\n    plt.figure(figsize=(8, 6))\n    plt.title(&quot;Network of Indian Cities&quot;)\n    for i in range(num_cities):\n        for j in range(num_cities):\n            if distances&#x5B;i]&#x5B;j] != INF:\n                plt.plot(&#x5B;i, j], &#x5B;j, i], &#039;k--&#039;, lw=0.5)\n                plt.text(i, j, str(distances&#x5B;i]&#x5B;j]), horizontalalignment=&#039;center&#039;, verticalalignment=&#039;center&#039;)\n    plt.xticks(range(num_cities), city_names)\n    plt.yticks(range(num_cities), city_names)\n    plt.xlabel(&quot;Cities&quot;)\n    plt.ylabel(&quot;Cities&quot;)\n    plt.grid(True)\n    plt.gca().invert_yaxis()\n    plt.show()\n\n# Function to print the shortest paths between all pairs of cities\ndef print_shortest_paths(dist, city_names):\n    print(&quot;Shortest distances between every pair of cities:&quot;)\n    for i in range(num_cities):\n        for j in range(num_cities):\n            if dist&#x5B;i]&#x5B;j] == INF:\n                print(&quot;Shortest distance from city {} to city {} is INF&quot;.format(city_names&#x5B;i], city_names&#x5B;j]))\n            else:\n                print(&quot;Shortest distance from city {} to city {} is {}&quot;.format(city_names&#x5B;i], city_names&#x5B;j], dist&#x5B;i]&#x5B;j]))\n\n# Define the distances between cities in the network\ndistances = np.array(&#x5B;&#x5B;0, 10, 15],\n                      &#x5B;INF, 0, 5],\n                      &#x5B;INF, INF, 0]])\n\n# Define the names of Indian cities\ncity_names = &#x5B;&#039;Mumbai&#039;, &#039;Delhi&#039;, &#039;Bangalore&#039;]\n\n# Find the shortest paths between all pairs of cities\nshortest_paths = find_shortest_paths(distances)\n\n# Print the shortest paths\nprint_shortest_paths(shortest_paths, city_names)\n\n# Plot the network of cities and roads\nplot_city_network(distances, city_names)\n\n<\/pre><\/div>\n\n\n<p>Let us look at the output.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"747\" height=\"547\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Floyd-Warshall-case-study-output.png\" alt=\"Floyd Warshall Case Study Output\" class=\"wp-image-62062\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Floyd-Warshall-case-study-output.png 747w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Floyd-Warshall-case-study-output-300x220.png 300w\" sizes=\"auto, (max-width: 747px) 100vw, 747px\" \/><figcaption class=\"wp-element-caption\"><strong><em>Floyd Warshall Case Study Output<\/em><\/strong><\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Now you know Floyd Warshall&#8217;s algorithm and how to use it to solve real-life problems. We also learned how to implement this concept in Python. How can the Floyd-Warshall algorithm be extended or modified to handle dynamic or time-varying networks, where the edge weights or connectivity may change over time? <\/p>\n\n\n\n<p><strong><em>Recommended: <a href=\"https:\/\/www.askpython.com\/python\/examples\/delivery-route-optimization-python\">Delivery Route Optimization using Python: A Step-by-Step Guide<\/a><\/em><\/strong><\/p>\n\n\n\n<p><strong><em>Recommended: <a href=\"https:\/\/www.askpython.com\/python\/examples\/capm-implementation-python\">Understanding the Capital Asset Pricing Model (CAPM)<\/a><\/em><\/strong><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Floyd-Warshall algorithm is a renowned technique for finding the shortest paths between all pairs of nodes in a weighted graph or network. We can solve complex routing problems and optimize various processes by using this algorithm. In this article, we&#8217;ll explore the underlying principles of the Floyd-Warshall algorithm and its implementation in Python, along [&hellip;]<\/p>\n","protected":false},"author":80,"featured_media":63869,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-62047","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/62047","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/80"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=62047"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/62047\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/63869"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=62047"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=62047"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=62047"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}