By wiki, Floyd-Warshall is a graph analysis algorithm for finding shortest paths in a weighted, directed graph. A single execution of the algorithm will find the shortest paths between all pairs of vertices. The Floyd–Warshall algorithm is an example of dynamic programming.
1 /* Assume a function edgeCost(i,j) which returns the cost of the edge from i to j
2 (infinity if there is none).
3 Also assume that n is the number of vertices and edgeCost(i,i)=0
4 */
5
6 int path[][];
7 /* A 2-dimensional matrix. At each step in the algorithm, path[i][j] is the shortest path
8 from i to j using intermediate values in (1..k-1). Each path[i][j] is initialized to
9 edgeCost(i,j).
10 */
11
12 procedure FloydWarshall ()
13 for k: = 0 to n − 1
14 for each (i,j) in (0..n − 1)
15 path[i][j] = min ( path[i][j], path[i][k]+path[k][j] );
For numerically meaningful output, Floyd-Warshall assumes that there are no negative cycles (in fact, between any pair of vertices which form part of a negative cycle, the shortest path is not well-defined because the path can be infinitely small). Nevertheless, if there are negative cycles, Floyd–Warshall can be used to detect them. A negative cycle can be detected if the path matrix contains a negative number along the diagonal. If path[i][i] is negative for some vertex i, then this vertex belongs to at least one negative cycle.
Applications:
Shortest Path Problems:
int Floyd_Warshall (int n) {
for(int k = 0; k < n; ++k)
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++ j)
G[i][j] = min(G[i][j], G[i][k] + G[k][j]);
}
- topCoder: MoneyExchange
- UVa 104: Arbitrage
- UVa 436: Arbitrage (II)
- UVa 423: MPI Maelstrom
- UVa 567: Risk
Transitive Closure/Hull
for(int k = 0; k < N; ++k)
for(int i = 0; i < N; ++i)
for(int j = 0; j < N; ++j)
G[i][j] = G[i][j] || (G[i][k] && G[k][j]);
- UVa 334: Identifying concurrent events
Minmax/ Maxmin distance
void minmax(int n) {for(int k = 0; k < n; ++k)
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
G[i][j] = min(G[i][j], max(G[i][k], G[k][j]));
}
- UVa 534: Frogger
- UVa 10048: Audiophobia
- UVa 544: Heavy Cargo
- UVa 10099: The Tourist Guide
void maxmin(int n) {
for(int k = 0; k < n; ++k)
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
G[i][j] = max(G[i][j], min(G[i][k], G[k][j]));
}
for(int k = 0; k < n; ++k)
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
G[i][j] = max(G[i][j], min(G[i][k], G[k][j]));
}