#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include<cstdlib>
#define MAX_VRETEX_NUM 20
#define MaxInt 32767
#define MVNum 50
typedef struct
{
int vexs[MVNum];
int arcs[MVNum][MVNum];
int vexnum, arcnum;
}AMGraph;
int LocateVex(AMGraph G, int v)
{
for (int i = 0; i < G.vexnum; i++) {
if (v == G.vexs[i])
return i;
}
return -1;
}
void CreateDN(AMGraph &G)
{
int i,j,k,w;
int v1, v2;
cout << "请输入顶点数和边数:" << endl;
cin >> G.vexnum >> G.arcnum;
cout << "请输入顶点的值:" << endl;
for (i = 0; i < G.vexnum; ++i)
cin >> G.vexs[i];
for (i = 0; i < G.vexnum; ++i)
for (j = 0; j < G.vexnum; ++j)
G.arcs[i][j] = MaxInt;
cout << "请输入边连接的顶点以及他们的权值:" << endl;
for (k = 0; k < G.arcnum; ++k)
{
cin >> v1 >> v2 >> w;
i = LocateVex(G, v1);
j = LocateVex(G, v2);
G.arcs[i][j] = w;
}
}
void ShortestPath_Dijkstra(AMGraph G, int v1, int v2)
{
int n = G.vexnum;
int a2, a3,i,v;
int w;
int m = 1;
a2 = LocateVex(G, v1);
a3 = LocateVex(G, v2);
int *path=new int[n];
int *s=new int[n];
int *d=new int[n];
for (v = 0; v < n; v++)
{
s[v] = 0;
d[v] = G.arcs[a2][v];
if (d[v] < MaxInt)
path[v] = a2;
else
path[v] = -1;
}
s[a2] = 1;
d[a2] = 0;
for (i = 1; i < n; ++i)
{
int min = MaxInt;
for (w = 0; w < n; ++w)
if (s[w] == 0 && d[w] < min)
{
v = w;
min = d[w];
}
s[v] = 1;
for (int w = 0; w < n; ++w)
{
if (s[w] == 0 && (d[v] + G.arcs[v][w] < d[w]))
{
d[w] = d[v] + G.arcs[v][w];
path[w] = v;
}
}
}
int *k = new int[n];
k[0] = path[a3];
cout << "直接路径为:" << endl;
if ((k[0]) != a2)
{
if(k[m]!=a2)
{
int k1 = k[m - 1];
k[m] = path[k1];
m++;
}
}
for (int j = m - 1; j >= 0; j--)
{
int h2 = k[j];
cout << G.vexs[h2] << "--";
}
cout << v2;
cout << endl;
cout << "需要时间为: " << endl;
cout << d[a3] << endl;
delete[]k;
}
void show()
{
cout << "地图如下图:" << endl;
cout << " [16] " << endl;
cout << " -----------------> " << endl;
cout << " (1) (2) " << endl;
cout << " | * <----------------- | * " << endl;
cout << " | | [29] | | " << endl;
cout << " [15] | | | | " << endl;
cout << " | | [21] [13] | |[27] " << endl;
cout << " | | | | " << endl;
cout << " | | | | " << endl;
cout << " * | [19] * | " << endl;
cout << " <----------------- " << endl;
cout << " (3) (4) " << endl;
cout << " -----------------> " << endl;
cout << " [7] " << endl;
}
int main()
{
AMGraph G;
CreateDN(G);
int v1, v2;
show();
cout << "请输入起点和终点,用空格隔开: " << endl;
while (1)
{
cout << "请再次输入:" << endl;
cin >> v1 >> v2;
ShortestPath_Dijkstra(G, v1, v2);
}
system("pause");
return 0;
}
最短路径,邻接矩阵请设计一个最佳路径导航功能,根据用户输入的起始点,输出最佳路径,以及需要的时间。
最新推荐文章于 2023-06-11 12:19:10 发布