templates/floyd-warshall.cpp
compilable
$cat templates/floyd-warshall
Floyd-Warshall
All-pairs shortest paths via O(V^3) dynamic programming on the adjacency matrix.
#floyd-warshall#all-pairs#shortest-path#dp#graph
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 1e18;
const int MAXN = 505;
ll dist[MAXN][MAXN];
int n;
void init() {
for (int i = 0; i < MAXN; i++)
for (int j = 0; j < MAXN; j++)
dist[i][j] = (i == j) ? 0 : INF;
}
void addEdge(int u, int v, ll w) {
dist[u][v] = min(dist[u][v], w);
}
void floydWarshall() {
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
}25 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Floyd-Warshall
All-pairs shortest paths in . Works with negative weights (no negative cycles).
Recurrence
Iterate as the intermediate node over all vertices. After iterations, is the shortest path using only vertices as intermediates.