#include "iostream"
#define n 5
#define INF 0x3f3f3f3f
using namespace std;
void display(int G[][n], int path[][n]);
void dfs(int path[][n], int i, int j);
void Floyd(int G[][n], int path[][n]) {
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (G[i][j] > G[i][k] + G[k][j]) {
G[i][j] = G[i][k] + G[k][j];
path[i][j] = k;
}
}
}
}
}
int main() {
int G[][n] = {{0, INF, 1, INF, 10},
{INF, 0, INF, 1, 5},
{INF, 1, 0, INF, 7,},
{INF, INF, INF, 0, 1},
{INF, INF, INF, INF, 0}};
int path[][n] = {{-1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1}};
cout << "------------------- print before_Floyd -------------------" << endl;
display(G, path);
Floyd(G, path);
cout << "------------------- print after_Floyd -------------------" << endl;
display(G, path);
cout << "\t\t\t\t--------- print path ---------\t\t\t\t" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (G[i][j] == INF || G[i][j] == 0) {
continue;
} else {
printf("V%d -> V%d(weight:%d) : V%d", i, j, G[i][j], i);
dfs(path, i, j);
printf("->V%d\n", j);
}
}
}
}
void dfs(int path[][n], int i, int j) {
if (path[i][j] != -1) {
int k = path[i][j];
dfs(path, i, k);
printf("->V%d", k);
dfs(path, k, j);
} else {
}
}
void display(int G[][n], int path[][n]) {
cout << "G[][] :\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (G[i][j] == INF)
cout << "INF" << "\t";
else
cout << G[i][j] << "\t";
}
cout << endl;
}
cout << "\nPath[][] :\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << path[i][j] << "\t";
}
cout << endl;
}
}
测试用例图示如下
程序输出如下
------------------- print before_Floyd -------------------
G[][] :
0 INF 1 INF 10
INF 0 INF 1 5
INF 1 0 INF 7
INF INF INF 0 1
INF INF INF INF 0
Path[][] :
-1 -1 -1 -1 -1
-1 -1 -1 -1 -1
-1 -1 -1 -1 -1
-1 -1 -1 -1 -1
-1 -1 -1 -1 -1
------------------- print after_Floyd -------------------
G[][] :
0 2 1 3 4
INF 0 INF 1 2
INF 1 0 2 3
INF INF INF 0 1
INF INF INF INF 0
Path[][] :
-1 2 -1 2 3
-1 -1 -1 -1 3
-1 -1 -1 1 3
-1 -1 -1 -1 -1
-1 -1 -1 -1 -1
--------- print path ---------
V0 -> V1(weight:2) : V0->V2->V1
V0 -> V2(weight:1) : V0->V2
V0 -> V3(weight:3) : V0->V2->V1->V3
V0 -> V4(weight:4) : V0->V2->V1->V3->V4
V1 -> V3(weight:1) : V1->V3
V1 -> V4(weight:2) : V1->V3->V4
V2 -> V1(weight:1) : V2->V1
V2 -> V3(weight:2) : V2->V1->V3
V2 -> V4(weight:3) : V2->V1->V3->V4
V3 -> V4(weight:1) : V3->V4
Process finished with exit code 0
|