All topics
100

Floyd-Warshall: every pair at once

Tier 1Locked

Where it runs

1. The problem

The last lesson (Bellman-Ford, step 99) and Dijkstra (step 97) answer the same question: from ONE start node, how far is every other node? One run gives one row of distances.

Sometimes you need the whole table: the distance from every place to every other place. Example: a courier depot has 40 pickup points. It wants the cost of the trip between any two of them, so it can plan any route the moment someone asks. That is n start points, and the answer is a grid of n by n numbers.

You could run Dijkstra once from each node. Floyd-Warshall fills the whole grid with one short triple loop (three loops, one inside the other). The code stays simple when the graph is small and dense, which means it has many edges.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included

On LeetCode

Problems that need the shortest distance between every pair of nodes, or which nodes can reach which, on a graph of a few hundred nodes at most. Three nested loops with the middle node outermost fill the whole table in n^3 steps.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy