弗洛伊德算法实现c语言
时间: 2023-11-27 09:47:50 浏览: 104
以下是使用C语言实现弗洛伊德算法的代码:
```c
#include <stdio.h>
#define Max_Int 32767
#define MAX_VERTEX_NUM 20
typedef struct {
int arcs[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vexnum, arcnum;
char vex[MAX_VERTEX_NUM];
} AMGraph;
int D[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
void CreateUDN(AMGraph *G) {
int i, j, k, w;
printf("请输入顶点数和边数:");
scanf("%d%d", &G->vexnum, &G->arcnum);
printf("请输入顶点信息:");
for (i = 0; i < G->vexnum; i++) {
scanf(" %c", &G->vex[i]);
}
for (i = 0; i < G->vexnum; i++) {
for (j = 0; j < G->vexnum; j++) {
G->arcs[i][j] = Max_Int;
}
}
printf("请输入边的信息:\n");
for (k = 0; k < G->arcnum; k++) {
printf("请输入第%d条边的起点、终点和权值:", k + 1);
scanf("%d%d%d", &i, &j, &w);
G->arcs[i][j] = w;
G->arcs[j][i] = w;
}
}
void ShortestPath_Floyd(AMGraph G) {
int i, j, k;
for (i = 0; i < G.vexnum; i++) {
for (j = 0; j < G.vexnum; j++) {
D[i][j] = G.arcs[i][j];
}
}
for (k = 0; k < G.vexnum; k++) {
for (i = 0; i < G.vexnum; i++) {
for (j = 0; j < G.vexnum; j++) {
if (D[i][j] > D[i][k] + D[k][j]) {
D[i][j] = D[i][k] + D[k][j];
}
}
}
}
}
int main(void) {
int i, j;
AMGraph G;
CreateUDN(&G);
ShortestPath_Floyd(G);
for (i = 1; i < G.vexnum; i++) {
if (D[0][i] == Max_Int) {
printf("0无法到达%c\n", G.vex[i]);
} else {
printf("0到%c的权值为:%d\n", G.vex[i], D[0][i]);
}
}
return 0;
}
```
阅读全文