The Floyd-Warshall Algorithm is an algorithm that computes the length of the shortest path between every pair of vertices in a graph with edge weights in time and space.

Hint

If the edge weights are non-negative, this problem can also be solved by Dijkstra’s Algorithm in

  • time and space, or
  • and space.

Algorithm 0

Let , denote the length of the shortest path from to that only passes through vertices . Then it is easy to prove that

and

Therefore, computing yields an algorithm that solves the problem in time and space.

std::vector dist(n + 1, std::vector(n, std::vector(n, inf)));
for (auto [u, v, w] : edges) {
	dist[0][u][v] = w;
}
for (int k = 0; k < n; k++) {
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			dist[k + 1][i][j] = std::min(dist[k][i][j], dist[k][i][k] + dist[k][k][j]);
		}
	}
}
return dist[n];

Algorithm 1

Lemma

Based on Algorithm 0, applying the lemma yields an algorithm that solves the problem in time and space.

std::vector dist(n, std::vector(n, inf));
for (auto [u, v, w] : edges) {
	dist[u][v] = w;
}
for (int k = 0; k < n; k++) {
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			dist[i][j] = std::min(dist[i][j], dist[i][k] + dist[k][j]);
		}
	}
}
return dist;