/**
* @Author: 郑潮安yyds
* @Time: 2021/12/2 18:47.
* @Filename: Floyd.cpp
* @Software: CLion
*/
#include <stdio.h>
#include <stdlib.h>
#define MAXN 100
#define INF 0x3f3f3f3f
typedef struct struct_graph {
char vexs[MAXN];
int vexnum;//顶点数
int edgnum;//边数
int matirx[MAXN][MAXN];//邻接矩阵
} Graph;
int pathmatirx[MAXN][MAXN];//记录对应点的最小路径的前驱点,例如p(1,3) = 2 说明顶点1到顶点3的最小路径要经过2
int shortPath[MAXN][MAXN];//记录顶点间的最小路径值
void short_path_floyd(Graph G, int P[MAXN][MAXN], int D[MAXN][MAXN]) {
//初始化floyd算法的两个矩阵
for (int v = 1; v <= G.vexnum; v++) {
for (int w = 1; w <= G.vexnum; w++) {
if (v == w) D[v][w] = 0;
else if (G.matirx[v][w] == 0) D[v][w] = INF;
else D[v][w] = G.matirx[v][w];
P[v][w] = w;
}
}
//这里是弗洛伊德算法的核心部分
//k为中间点
for (int k = 1; k <= G.vexnum; k++) {
//v为起点
for (int v = 1; v <= G.vexnum; v++) {
//w为终点
for (int w = 1; w <= G.vexnum; w++) {
if ((D[v][k] + D[k][w]) < D[v][w]) {
D[v][w] = D[v][k] + D[k][w];//更新最小路径
P[v][w] = P[v][k];//更新最小路径中间顶点
}
}
}
}
printf("\nD矩阵\n");
for (int v = 1; v <= G.vexnum; v++) {
for (int w = 1; w <= G.vexnum; w++) {
printf("%10d ", D[v][w]);
}
printf("\n");
}
printf("\nP矩阵\n");
for (int v = 1; v <= G.vexnum; v++) {
for (int w = 1; w <= G.vexnum; w++) {
printf("%10d", P[v][w]);
}
printf("\n");
}
}
int main() {
freopen("C:\\Users\\30414\\Desktop\\LuoguWeek3\\input.in", "r", stdin);
int from, to, weight;
Graph G;
printf("请输入顶点数:\n");
scanf("%d", &G.vexnum);
printf("请输入边数:\n");
scanf("%d", &G.edgnum);
for (int i = 1; i <= G.edgnum; i++) {
scanf("%d %d %d", &from, &to, &weight);
G.matirx[from][to] = weight;
}
short_path_floyd(G, pathmatirx, shortPath);
int v = 1, w = 3;
printf("请输入你想要的起点和终点:\n");
scanf("%d %d", &v, &w);
printf("\n%d -> %d 的最小路径为:%d\n", v, w, shortPath[v][w]);
int k = pathmatirx[v][w];
printf("path: %d", v);//打印起点
while (k != w) {
printf("-> %d", k);//打印中间点
k = pathmatirx[k][w];
}
printf("-> %d\n", w);
return 0;
}
8_Floyd算法
最新推荐文章于 2024-08-25 18:17:58 发布