Pagini recente » Cod sursa (job #1904878) | Cod sursa (job #3002267) | Cod sursa (job #3256932) | Cod sursa (job #2514310) | Cod sursa (job #3276761)
#include <iostream>
#include <fstream>
#include <vector>
#include <climits> // For INT_MAX
using namespace std;
int main()
{
ifstream fin("royfloyd.in");
ofstream fout("royfloyd.out");
int n;
fin >> n;
vector<vector<int>> D(n + 1, vector<int>(n + 1, INT_MAX));
// Initialize the graph distances
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
fin >> D[i][j];
if (D[i][j] == 0 && i != j) {
D[i][j] = INT_MAX; // Set to infinity if no path (except for diagonal)
}
}
}
// Floyd-Warshall Algorithm
for(int k = 1; k <= n; k++) {
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if(D[i][j] > D[i][k] + D[k][j]) {
D[i][j] = D[i][k] + D[k][j];
}
}
}
}
// Output the shortest path matrix
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if (D[i][j] == INT_MAX) {
fout << "0 "; // For unreachable paths
} else {
fout << D[i][j] << ' ';
}
}
fout << endl;
}
return 0;
}