Pagini recente » Cod sursa (job #3281235) | Cod sursa (job #2249180) | Cod sursa (job #2936277) | Cod sursa (job #2164362) | Cod sursa (job #3221538)
#include <fstream>
#define MAX_DIMENSION 100
#define INF 0x7f7f7f7f
using namespace std;
ifstream fin("royfloyd.in");
ofstream fout("royfloyd.out");
int mat[MAX_DIMENSION + 1][MAX_DIMENSION + 1];
void floydWarshall(int nrNodes) {
for (int node = 1; node <= nrNodes; ++node) {
for (int row = 1; row <= nrNodes; ++row) {
if (row != node) {
for (int col = 1; col <= nrNodes; ++col) {
if (col != node) {
mat[row][col] = min(mat[row][col], mat[row][node] + mat[node][col]);
}
}
}
}
}
}
/*
* According to the problem description, if a path between two nodes is 0, then this means there is no path between them.
* In case there is still no path between 2 nodes even after applying the algorithm, then we mark their distance as being 0.
*/
void printAllPairsShortestDistances(int nrNodes) {
for (int row = 1; row <= nrNodes; ++row) {
for (int col = 1; col <= nrNodes; ++col) {
if (mat[row][col] == INF) {
mat[row][col] = 0;
}
fout << mat[row][col] << ' ';
}
fout << '\n';
}
}
int main() {
int nrNodes;
fin >> nrNodes;
for (int row = 1; row <= nrNodes; ++row) {
for (int col = 1; col <= nrNodes; ++col) {
fin >> mat[row][col];
if (row != col && mat[row][col] == 0) {
mat[row][col] = INF; // mark this non-existent edge between two nodes(i.e. row and col)
}
}
}
floydWarshall(nrNodes);
printAllPairsShortestDistances(nrNodes);
return 0;
}