Pagini recente » Cod sursa (job #2881683) | Cod sursa (job #3138538) | Cod sursa (job #1382140) | Cod sursa (job #1910280) | Cod sursa (job #3272284)
#include <fstream>
#include <vector>
#include <algorithm>
#include <climits>
#define INFINIT 1000000
using namespace std;
ifstream fin("royfloyd.in");
ofstream fout("royfloyd.out");
class Graf {
private:
int nrNoduri;
vector<int> *adiacenta;
public:
explicit Graf(int nrNoduri);
vector<vector<int>> royFloyd(vector<vector<int>> &matrice);
~Graf();
};
Graf::Graf(const int nrNoduri) {
this->nrNoduri = nrNoduri;
this->adiacenta = nullptr;
}
vector<vector<int>> Graf::royFloyd(vector<vector<int>> &matrice) {
vector<vector<int>> distante = matrice;
// Replace 0 (no edge) with INFINIT, except on the diagonal
for (int i = 1; i <= nrNoduri; i++) {
for (int j = 1; j <= nrNoduri; j++) {
if (i != j && distante[i][j] == 0) {
distante[i][j] = INFINIT;
}
}
}
// Floyd-Warshall Algorithm
for (int k = 1; k <= nrNoduri; k++) {
for (int i = 1; i <= nrNoduri; i++) {
for (int j = 1; j <= nrNoduri; j++) {
if (distante[i][k] < INFINIT && distante[k][j] < INFINIT) {
distante[i][j] = min(distante[i][j], distante[i][k] + distante[k][j]);
}
}
}
}
// Replace INFINIT back to 0 for unreachable nodes
for (int i = 1; i <= nrNoduri; i++) {
for (int j = 1; j <= nrNoduri; j++) {
if (distante[i][j] == INFINIT) {
distante[i][j] = 0;
}
}
}
return distante;
}
Graf::~Graf() {
delete[] adiacenta;
}
int main() {
int n;
fin >> n; // Number of nodes
vector<vector<int>> matriceCosturi(n + 1, vector<int>(n + 1)); // Adjacency matrix
// Read input matrix
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
fin >> matriceCosturi[i][j];
}
}
Graf g(n);
vector<vector<int>> distante = g.royFloyd(matriceCosturi);
// Output the shortest path matrix
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
fout << distante[i][j] << " ";
}
fout << "\n";
}
fin.close();
fout.close();
return 0;
}