Pagini recente » Cod sursa (job #1527612) | Cod sursa (job #1444658) | Cod sursa (job #1545214) | Cod sursa (job #2112373) | Cod sursa (job #2312750)
/* Floyd-Warshall algorithm O(V^3)
- computes shortest path between all pairs of 2 nodes
*/
#include <bits/stdc++.h>
FILE *fin = freopen("royfloyd.in", "r", stdin);
FILE *fout = freopen("royfloyd.out", "w", stdout);
using namespace std;
const int Vmax = 102;
const int oo = INT_MAX;
int nodes;
int dist[Vmax][Vmax];
void floyd_warshall() {
for (int k = 0; k < nodes; ++ k) // iteratively add node k to the set of intermediate vertices
for (int i = 0; i < nodes; ++ i) // iterate through source vertices
for (int j = 0; j < nodes; ++ j) // iterate through destination vertices
if (dist[i][k]!= oo && dist[k][j] != oo &&
dist[i][j] > dist[i][k] + dist[k][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
int main() {
scanf("%d", &nodes);
for (int i = 0; i < nodes; ++i) // read the adjacency matrix
for(int j = 0; j < nodes; ++j) {
scanf("%d", &dist[i][j]);
if(!dist[i][j] && i!=j) dist[i][j] = oo;
}
floyd_warshall();
for (int i = 0; i < nodes; ++i) { // print the shortest path matrix
for(int j = 0; j < nodes; ++j) {
if(dist[i][j]==oo)
printf("0 ");
else printf("%d ", dist[i][j]);
}
printf("\n");
}
return 0;
}