All pairs shortest path (Floyd's)
All Pairs Shortest Path (Floyd-Warshall Algorithm)
Introduction
For a given connected weighted graph , the All Pairs Shortest Path (APSP) problem aims to find the shortest path between every pair of vertices.
Floyd–Warshall is a classic algorithm for solving All Pairs Shortest Path.
It works for both directed and undirected graphs, as long as the graph does not contain a negative cycle.
Weight Matrix

Let the weight matrix be:
Each entry is:
Where:
= weight of edge
Distance Matrices
The algorithm computes a series of matrices:
Here:
stores the shortest path distances between every pair
Intermediate vertices allowed must be numbered ≤ k
So,
Recursive Relation
Each entry in matrix is computed using values from :
Interpretation:
First value: shortest path from without using vertex
Second value: shortest path from using vertex
We pick the shorter one.
Meaning
For step , we check whether including vertex as an intermediate point gives a shorter route between every pair . If yes, update it.
Algorithm
floydWarshall(weightMatrix[n][n])
{
// Input : Weight matrix W for given weighted connected graph G(V, E)
// Output : D the distance matrix
for k = 1 to n do
{
for i = 1 to n do
{
for j = 1 to n do
{
D[i][j] = min(D[i][j], D[i][k] + D[k][j])
}
}
}
return D
}The time complexity of algorithm is big since there are three nested loop each with an iteration
For the given problem, the number of nodes is:
The graph is a directed weighted graph.
We first construct the weight matrix for the given graph.
Recursive Relation
To compute from :
To find the distance metric, we compute a sequence of metrices
D0, D1, D2, D3 D4
Where matrix D4 is the distance matrix and D0 = W (the weight matrix)
“ has the entries which give the distance between every pair of vertices of the graph, where the intermediate node (if any) has a number not higher than .”
The main matrix is the distance matrix, which provides the shortest distance between any pair of vertices.
Note: distance between is zero always.
