38 lines
1.4 KiB
Plaintext
38 lines
1.4 KiB
Plaintext
// NOTE: Check the input graph for multiple edges between the same vertices! You will want to keep the shortest one
|
|
// Time complexity: O(n^3)
|
|
// Memory complexity: O(n^2) - only for n ~ 10^3 (n ~ 10^4 results in 1524 MB of memory)
|
|
// Input: Graph as an adjancency matrix (weight __LONG_MAX__ => no edge)
|
|
// Output: A distance matrix (distance __LONG_MAX__ => no path)
|
|
vector<vector<long>> floyd_warshall(vector<vector<long>> adj) {
|
|
size_t n = adj.size();
|
|
vector<vector<long>> distance(n, vector<long>(n, 0));
|
|
|
|
// Initialize distance
|
|
for (size_t i = 0; i < n; i++) {
|
|
for (size_t j = 0; j < n; j++) {
|
|
// Original floyd-warshall
|
|
// if (i == j) distance[i][j] = 0;
|
|
// else if (adj[i][j]) distance[i][j] = adj[i][j];
|
|
// else distance[i][j] = __LONG_MAX__;
|
|
|
|
// My version
|
|
if (i == j) distance[i][j] = 0;
|
|
else distance[i][j] = adj[i][j];
|
|
}
|
|
}
|
|
|
|
// Find shortest distances
|
|
for (size_t k = 0; k < n; k++) {
|
|
for (size_t i = 0; i < n; i++) {
|
|
for (size_t j = 0; j < n; j++) {
|
|
if (distance[i][k] == __LONG_MAX__ || distance[k][j] == __LONG_MAX__)
|
|
continue;
|
|
distance[i][j] = min(distance[i][j],
|
|
distance[i][k] + distance[k][j]);
|
|
}
|
|
}
|
|
}
|
|
|
|
return distance;
|
|
}
|