图的最短路径问题
作者:互联网
#include<iostream>
#include<cstring>
using namespace std;
#define MaxInt 32767
#define MVNum 100
typedef char VerTexType[20];
typedef int ArcType;
int Path[MVNum][MVNum];
int D[MVNum][MVNum];
typedef struct {
VerTexType vexs[MVNum];
ArcType arcs[MVNum][MVNum];
int vexnum, arcnum;
}AMGraph;
int LocateVex(AMGraph G, VerTexType v)
{
for (int i = 0; i < G.vexnum; i++)
{
if (!strcmp(G.vexs[i], v))
{
return i;
}
}
return -1;
}
void CreateUDN(AMGraph& G)
{
cout << "请输入总标志点数,总可通道路数:";
cin >> G.vexnum >> G.arcnum;
cout << "输入标志点的名称" << endl;
for (int i = 0; i < G.vexnum; i++)
{
cout << "请输入第" << i + 1 << "个标志点的名称:";
cin >> G.vexs[i];
}
cout << endl;
for (int i = 0; i < G.vexnum; i++)
{
for (int j = 0; j < G.vexnum; j++)
{
if (j != i)
{
G.arcs[i][j] = MaxInt;
}
else
{
G.arcs[i][j] = 0;
}
}
}
cout << "输入道路依附的标志点及权值" << endl;
for (int k = 0; k < G.arcnum; k++)
{
VerTexType v1, v2;
ArcType w;
cout << "请输入第" << k + 1 << "条道路依附的标志点及路长:";
cin >> v1 >> v2 >> w;
int i = LocateVex(G, v1);
int j = LocateVex(G, v2);
G.arcs[i][j] = G.arcs[j][i] = 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 (D[i][j] < MaxInt && i != 1)
{
Path[i][j] = 1; //如果i和j之间有弧,则将j的前驱置为i
}
else
{
Path[i][j] = -1; //如果i和j之间无弧,则将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]) //从i经k到j的一条路径更短
{
D[i][j] = D[i][k] + D[k][j];
Path[i][j] = Path[k][j];
}
}
}
}
}
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()
{
cout << "***********图及其应用(校园导航)**********" << endl;
AMGraph G;
char start[20], destination[20];
int num_start, num_destination ;
CreateUDN(G);
ShortestPath_Floyed(G);
cout << "请依次输入路径的起点与终点的名称:";
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] << endl;
return 0;
}
标签:vexnum,cout,int,路径,MVNum,问题,++,Path 来源: https://blog.csdn.net/weixin_54418006/article/details/122016497