#include<iostream>
using namespace std;
#define MaxInt 32767
#define MVNum 100
typedef char VerTexType;
typedef int ArcType;
int Path[MVNum][MVNum]; //标志两个结点之间是否可达
int D[MVNum][MVNum];//存储两个结点间的边的权重
typedef struct{
VerTexType vexs[MVNum];//结点名称
ArcType arcs[MVNum][MVNum];//边的位置
int vexnum,arcnum; //结点个数,边的个数
}AMGraph;
void CreateUDN(AMGraph& G) {
cin >> G.vexnum;
cin >> G.arcnum;
for (int i = 0; i < G.vexnum; i++) {
cin >> G.vexs[i];//输入各个结点各自的名称(字符类型)
}
for (int i = 0; i < G.vexnum; i++) {
for (int j = 0; j < G.vexnum; j++) {
G.arcs[i][j] = MaxInt;//初始化各条边,初始化为不可达
}
}
for (int k = 0; k < G.arcnum; k++) {//创建有向邻接矩阵
int i, j, w;
cin >> i >> j >> w;
G.arcs[i][j] = w;
}
}
void ShortestPath_Floyed(AMGraph G) {//最短路径核心算法--弗洛伊德算法
for (int i = 0; i < G.vexnum; i++) {
for (int j = 0; j < G.vexnum; j++) {
D[i][j] = G.arcs[i][j];
if (i != j && G.arcs[i][j] < MaxInt) {
Path[i][j] = i;//标志为其正经权重
} else {
Path[i][j] = -1;//标志位不可达
}
}
}
for (int k = 0; k < G.vexnum; k++) {
for (int i = 0; i < G.vexnum; i++) {
for (int j = 0; j < G.vexnum; j++) {
if (D[i][k] + D[k][j] < D[i][j]) {//找寻最短路径
D[i][j] = D[i][k] + D[k][j];//更换最短路径
Path[i][j] = Path[k][j];//更换对应标志
}
}
}
}
}
int LocateVex(AMGraph G, VerTexType v) {//定位某个结点的位置
for (int i = 0; i < G.vexnum; i++) {
if (G.vexs[i] == v) {
return i;
}
}
return -1;
}
void DisplayPath(AMGraph G , int begin ,int temp ){//输出相应的运行结果
if(Path[begin][temp] != -1){
DisplayPath(G , begin ,Path[begin][temp]);
cout << G.vexs[Path[begin][temp]] << "->";
}
}
int main(){
AMGraph G;
char start , destination;
int num_start , num_destination;
CreateUDN(G);
ShortestPath_Floyed(G);
cin >> start >> destination;//输入源点和终点
num_start = LocateVex(G , start);
num_destination = LocateVex(G , destination);
DisplayPath(G , num_start , num_destination);//利用迭代算法寻找源点和终点的最短路径
cout << G.vexs[num_destination]<<endl;
cout << D[num_start][num_destination];
return 0;
}
标签:vexnum,弗洛伊德,start,int,MVNum,最短,++,算法,Path
From: https://www.cnblogs.com/liuzijin/p/17495348.html