{"id":405,"date":"2025-06-26T22:45:57","date_gmt":"2025-06-26T17:15:57","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=405"},"modified":"2025-06-26T22:45:59","modified_gmt":"2025-06-26T17:15:59","slug":"floyd-warshall-vs-dijkstra-all-pairs-shortest-paths","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/floyd-warshall-vs-dijkstra-all-pairs-shortest-paths\/","title":{"rendered":"Floyd Warshall vs. Multi-Source Dijkstra | Two Ways to Solve All-Pairs Shortest Paths"},"content":{"rendered":"\n<p>Master Floyd Warshall for APSP and see when a Dijkstra-per-source loop beats it. Clear intuition, Python code, and complexity breakdown.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/www.geeksforgeeks.org\/problems\/implementing-floyd-warshall2042\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-d808f4f8-0e47-4ee9-b2fd-2aff0853e41b\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/floyd-warshall-vs-dijkstra-all-pairs-shortest-paths\/#0-1-problem-in-one-line\" style=\"\">1. Problem in one line<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/floyd-warshall-vs-dijkstra-all-pairs-shortest-paths\/#1-2-why-two-algorithms\" style=\"\">2. Why two algorithms?<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/floyd-warshall-vs-dijkstra-all-pairs-shortest-paths\/#2-3-intuition-amp-approach\" style=\"\">3. Intuition &amp; approach<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/floyd-warshall-vs-dijkstra-all-pairs-shortest-paths\/#3-31%E2%80%82floyd-warshall-dynamic-programming\" style=\"\">3.1\u2002Floyd Warshall (dynamic programming)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/floyd-warshall-vs-dijkstra-all-pairs-shortest-paths\/#4-32%E2%80%82dijkstra-run-n-times-\" style=\"\">3.2\u2002Dijkstra run n times<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/floyd-warshall-vs-dijkstra-all-pairs-shortest-paths\/#5-4-python-code\" style=\"\">4. Python code<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/floyd-warshall-vs-dijkstra-all-pairs-shortest-paths\/#6-41-floyd-warshall\" style=\"\">4.1 Floyd Warshall<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/floyd-warshall-vs-dijkstra-all-pairs-shortest-paths\/#7-42-multi-source-dijkstra\" style=\"\">4.2 Multi-Source Dijkstra<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/floyd-warshall-vs-dijkstra-all-pairs-shortest-paths\/#8-5-complexity-comparison\" style=\"\">5. Complexity comparison<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/floyd-warshall-vs-dijkstra-all-pairs-shortest-paths\/#9-6-dry-run-snippet-3-node-graph\" style=\"\">6. Dry-run snippet (3-node graph)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/floyd-warshall-vs-dijkstra-all-pairs-shortest-paths\/#10-7-conclusion\" style=\"\">7. Conclusion<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"0-1-problem-in-one-line\">1. Problem in one line<\/h2>\n\n\n\n<p>Given an <strong><em>n \u00d7 n<\/em><\/strong> weighted graph matrix <code>dist<\/code>, replace each <code>dist[i][j]<\/code> with the weight of the <strong>shortest path<\/strong> from vertex <code>i<\/code> to vertex <code>j<\/code>. <code>10**8<\/code> stands for \u201c\u221e\u201d.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-2-why-two-algorithms\">2. Why two algorithms?<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Goal<\/th><th>Works with negative edges?<\/th><th>Typical graph size<\/th><\/tr><\/thead><tbody><tr><td><strong>Floyd Warshall<\/strong> \u2013 triple-loop DP<\/td><td>\u2705 (no negative cycles)<\/td><td>small\/medium dense<\/td><\/tr><tr><td><strong>Dijkstra from every source<\/strong> \u2013 heap<\/td><td>\u274c (needs \u2265 0 weights)<\/td><td>larger sparse<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>We will implement both and compare.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-3-intuition-amp-approach\">3. Intuition &amp; approach<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-31%E2%80%82floyd-warshall-dynamic-programming\">3.1\u2002Floyd Warshall (dynamic programming)<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Consider every vertex <code>via<\/code> as a possible <strong>intermediate stop<\/strong>.<\/li>\n\n\n\n<li>For each pair <code>(i, j)<\/code> test whether going <code>i \u2192 via \u2192 j<\/code> is cheaper than the best path already known.<\/li>\n\n\n\n<li>Repeat for all <code>via \u2208 [0, n-1]<\/code>. After <code>n<\/code> rounds, every indirect shortcut is tried.<\/li>\n<\/ol>\n\n\n\n<p>This is classic <strong>DP on triples<\/strong> \u2013 indices mean \u201cshortest path that only uses<br>vertices \u2264 via as intermediates\u201d.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-32%E2%80%82dijkstra-run-n-times-\">3.2\u2002Dijkstra run <strong><code>n<\/code> times<\/strong><\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Convert the matrix to an adjacency list &#8212; skip <code>\u221e<\/code> entries.<\/li>\n\n\n\n<li>For each source <code>src<\/code> run standard <strong>min-heap Dijkstra<\/strong> to fill row <code>src<\/code>.<\/li>\n\n\n\n<li>Copy the row back into the matrix.<\/li>\n<\/ol>\n\n\n\n<p>Total complexity scales with <code>n<\/code> times the cost of one Dijkstra.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-4-python-code\">4. Python code<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-41-floyd-warshall\">4.1 Floyd Warshall<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def floydWarshall(self, dist):\n        n = len(dist)\n        INF = 10**8\n\n        for via in range(n):\n            for i in range(n):\n                for j in range(n):\n                    if dist[i][via] != INF and dist[via][j] != INF:\n                        dist[i][j] = min(dist[i][j],\n                                         dist[i][via] + dist[via][j])\n        return dist\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">floydWarshall<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">dist<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(dist)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        INF = <\/span><span style=\"color: #B5CEA8\">10<\/span><span style=\"color: #D4D4D4\">**<\/span><span style=\"color: #B5CEA8\">8<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> via <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> j <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> dist[i][via] != INF <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> dist[via][j] != INF:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                        dist[i][j] = <\/span><span style=\"color: #DCDCAA\">min<\/span><span style=\"color: #D4D4D4\">(dist[i][j],<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                                         dist[i][via] + dist[via][j])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> dist<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"7-42-multi-source-dijkstra\">4.2 Multi-Source Dijkstra<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"import heapq\n\nclass Solution:\n    INF = 10**8\n\n    def floydWarshall(self, dist):\n        &quot;&quot;&quot;Fill dist with shortest-path weights using Dijkstra per source.&quot;&quot;&quot;\n\n        n = len(dist)\n\n        # 1) build adjacency list once\n        adj = [[] for _ in range(n)]\n        for u in range(n):\n            for v, w in enumerate(dist[u]):\n                if u != v and w != self.INF:      # ignore self &amp; no-edge\n                    adj[u].append((v, w))\n\n        # 2) run Dijkstra from every vertex\n        for src in range(n):\n            best = [self.INF] * n\n            best[src] = 0\n            pq = [(0, src)]\n\n            while pq:\n                d, u = heapq.heappop(pq)\n                if d != best[u]:          # stale heap entry\n                    continue\n                for v, w in adj[u]:\n                    nd = d + w\n                    if nd &lt; best[v]:\n                        best[v] = nd\n                        heapq.heappush(pq, (nd, v))\n\n            dist[src][:] = best           # update the matrix row\n\n        return dist\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> heapq<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    INF = <\/span><span style=\"color: #B5CEA8\">10<\/span><span style=\"color: #D4D4D4\">**<\/span><span style=\"color: #B5CEA8\">8<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">floydWarshall<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">dist<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #CE9178\">&quot;&quot;&quot;Fill dist with shortest-path weights using Dijkstra per source.&quot;&quot;&quot;<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(dist)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># 1) build adjacency list once<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        adj = [[] <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n)]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> u <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> v, w <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">enumerate<\/span><span style=\"color: #D4D4D4\">(dist[u]):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> u != v <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> w != <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.INF:      <\/span><span style=\"color: #6A9955\"># ignore self &amp; no-edge<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    adj[u].append((v, w))<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># 2) run Dijkstra from every vertex<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> src <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            best = [<\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.INF] * n<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            best[src] = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            pq = [(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, src)]<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> pq:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                d, u = heapq.heappop(pq)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> d != best[u]:          <\/span><span style=\"color: #6A9955\"># stale heap entry<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">continue<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> v, w <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> adj[u]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    nd = d + w<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nd &lt; best[v]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                        best[v] = nd<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                        heapq.heappush(pq, (nd, v))<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            dist[src][:] = best           <\/span><span style=\"color: #6A9955\"># update the matrix row<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> dist<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"8-5-complexity-comparison\">5. Complexity comparison<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Algorithm<\/th><th>Time<\/th><th>Space<\/th><th>Pros<\/th><th>Cons<\/th><\/tr><\/thead><tbody><tr><td><strong>Floyd Warshall<\/strong><\/td><td><strong>O(n\u00b3)<\/strong><\/td><td>O(1) extra<\/td><td>Handles negative weights; tiny code<\/td><td>Cubic blow-up beyond ~400 vertices<\/td><\/tr><tr><td><strong><code>n<\/code>\u00d7Dijkstra (binary heap)<\/strong><\/td><td><strong>O(n \u00b7 (E log V))<\/strong> \u2192 about O(n\u00b2 log n) on dense graphs, O(n E log n) on sparse<\/td><td>O(E + n)<\/td><td>Fast on sparse, positive-weight graphs<\/td><td>Fails with negative edges<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><strong>Rule of thumb<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><em>Dense or negative edges?<\/em> \u2192 Floyd Warshall.<\/li>\n\n\n\n<li><em>Sparse with non-negative weights and n \u2273 500?<\/em> \u2192 Dijkstra per source.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"9-6-dry-run-snippet-3-node-graph\">6. Dry-run snippet (3-node graph)<\/h2>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"dist = [\n  [0,     4, 11],\n  [10,    0,  2],\n  [5,   INF,  0]\n]\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">dist = [<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">  [<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">,     <\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">11<\/span><span style=\"color: #D4D4D4\">],<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">  [<\/span><span style=\"color: #B5CEA8\">10<\/span><span style=\"color: #D4D4D4\">,    <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">,  <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">],<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">  [<\/span><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\">,   INF,  <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">]<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p><em>Floyd Warshall<\/em> finds path <code>0\u21921\u21922<\/code> = 6 replaces 11,<br>and <code>2\u21920\u21921<\/code> = 9 beats <code>INF<\/code>.<br>Final matrix:<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"0 4 6\n7 0 2\n5 9 0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">6<\/span><\/span>\n<span class=\"line\"><span style=\"color: #B5CEA8\">7<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">2<\/span><\/span>\n<span class=\"line\"><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">9<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p>Dijkstra loop yields the <strong>same<\/strong> matrix (because all weights \u2265 0).<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"10-7-conclusion\">7. Conclusion<\/h2>\n\n\n\n<p><em>The focus word <strong>Floyd Warshall<\/strong> stands for the all-pairs classic:<\/em><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>O(n\u00b3)<\/strong>, supports negative weights, trivially in-place.<\/li>\n\n\n\n<li><strong>Dijkstra-per-source<\/strong> trades that for speed on larger, positive-weight, sparse graphs.<\/li>\n<\/ul>\n\n\n\n<p>Pick the one that matches your graph\u2019s density and edge sign, and keep both techniques handy for interviews and contests.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Master Floyd Warshall for APSP and see when a Dijkstra-per-source loop beats it. Clear intuition, Python code, and complexity breakdown. Here&#8217;s the [Problem Link] to begin with. 1. Problem in one line Given an n \u00d7 n weighted graph matrix dist, replace each dist[i][j] with the weight of the shortest path from vertex i to<\/p>\n","protected":false},"author":1,"featured_media":406,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,5],"tags":[25,17],"class_list":{"0":"post-405","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-expert","9":"tag-floyd-warshall","10":"tag-graph"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/06\/floyd-warshall-algorithm-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/405","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=405"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/405\/revisions"}],"predecessor-version":[{"id":407,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/405\/revisions\/407"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/406"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=405"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=405"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=405"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}