#include<stdio.h>
#define MAX 100
typedef struct graph {
int vn;
char vertex[MAX];
int edge[MAX][MAX];
int cost[MAX][MAX];
int route[MAX][MAX];
} GH;
void floyd(GH *gh);
void putpath(GH * gh,int start,int end);
void update(GH *gh,char bridge);
int getindex(GH * gh,char target);
int main() {
int i = 0,j = 0;
GH grah;
GH * gh = &grah;
int visited[MAX] = {0};
char temp = '\0';
scanf("%d",&gh->vn);
temp = getchar();
for(i = 0; i < gh->vn; i++) {
scanf("%c",&gh->vertex[i]);
temp = getchar();
}
for(i = 0; i < gh->vn; i++) {
for(j = 0; j < gh->vn; j++) {
scanf("%d",&gh->cost[i][j]);
}
}
for(i = 0; i < gh->vn; i++) {
for(j = 0; j < gh->vn; j++) {
gh->route[i][j] = -1;
}
}
floyd(gh);
return 0;
}
void floyd(GH *gh) {
int i = 0,j = 0;
for(i = 0; i < gh->vn; i++) {
update(gh,gh->vertex[i]);
}
for(i = 0; i < gh->vn; i++) {
for(j = 0; j < gh->vn; j++) {
printf("%c",gh->vertex[i]);
putpath(gh,i,j);
printf("\n");
}
}
}
void putpath(GH * gh,int start,int end) {
if(gh->route[start][end] == -1) printf("->");
else {
putpath(gh,start,gh->route[start][end]);
printf("->");
}
printf("%c",gh->vertex[end]);
}
void update(GH *gh,char bridge) {
int i = 0,j = 0;
int inde = getindex(gh,bridge);
for(i = 0; i < gh->vn; i++) {
for(j = 0; j < gh->vn; j++) {
if(gh->cost[i][inde] + gh->cost[inde][j] < gh->cost[i][j]) {
gh->route[i][j] = inde;
}
}
}
}
int getindex(GH * gh,char target) {
int i = 0;
for(i = 0; i < gh->vn; i++) {
if(gh->vertex[i] == target) {
return i;
}
}
return -1;
}
floyd算法 ---- C语言
最新推荐文章于 2024-01-21 11:12:42 发布