#include <iostream>
#include <vector>
#define INFINITY 32768
#define VERTEX_MAX 50
using namespace std;
typedef char VertexType; //顶点类型
typedef int AdjType; //边的关系类型
typedef struct {
VertexType vertex[VERTEX_MAX]; //顶点集
AdjType arcs[VERTEX_MAX][VERTEX_MAX]; //边集
int vexnum,arcnum; //图的当前顶点数和弧数
}MGraph;
void CreateDNGraph(MGraph *G);
void ShortestPath_DJS(MGraph G,int v0,int dist[VERTEX_MAX],int path[VERTEX_MAX]);
int main()
{
MGraph G;
CreateDNGraph(&G);
int dist[VERTEX_MAX];
int path[VERTEX_MAX];
ShortestPath_DJS(G,0,dist,path);
return 0;
}
//求顶点位置函数
int LocateVex(MGraph *G,VertexType v)
{
int i;
for(i=0;i<G->vexnum;i++)
{
if(G->vertex[i] == v)
return i;
}
return -1;
}
//创建又向带权图
void CreateDNGraph(MGraph *G)
{
int i,j;
VertexType v1,v2;
int w;
cout<<"请输入顶点数和边数:";
cin>>G->vexnum>>G->arcnum;
cout<<"请输入各顶点的数据:";
for(int i=0;i<G->vexnum;i++)
cin>>G->vertex[i];
for (int i = 0; i < G->vexnum; i++)
{
for(int j=0;j< G->vexnum;j++)
G->arcs[i][j] = INFINITY;
}
cout<<"请输入"<<G->arcnum<<"对顶点和相应的权重:\n";
for(int k=0; k<G->arcnum; k++)
{
cin>>v1>>v2>>w;
i = LocateVex(G,v1);
j = LocateVex(G,v2);
if(i>=0 && j>=0)
G->arcs[i][j] = w;
}
}
//dist[i]:存放目前已经找到的,从开始点v0到终点vi的当前最短路径长度
//path[i]: 存放目前已经找到的,从开始点v0到终点vi的当前最短路径的顶点下标序列
void ShortestPath_DJS(MGraph G,int v0,int dist[VERTEX_MAX],int path[VERTEX_MAX])
{
int min,j,k;
int final[VERTEX_MAX]; //为1代表已求得v0到v的最短路径(最短路径的终点集合)
for (int i = 0; i < G.vexnum; i++)
{
final[i] = 0;
dist[i] = G.arcs[v0][i]; //将v0到各顶点的最短路径长度初始化为权值
if(dist[i]<INFINITY)
path[i] = v0; //初始化各顶点的最短路径为边(v0,vi)
}
final[v0] = 1; //讲顶点v0加入终点集合
dist[v0] = 0; //将最开始顶点(源点)的最短路径置为0
for (int i = 0; i < G.vexnum; i++)
{
min = INFINITY;
for (j = 0; j < G.vexnum; j++)
{
if (final[j]==0 && dist[j]<min) //查找未用顶点的最小权值
{
min = dist[j];
k = j;
}
}
final[k] = 1; //将顶点k加入终点集合
for(j=0;j<G.vexnum;j++)
{
//以顶点k为中间点,重新计算权重
if (final[j]==0 && dist[k]+G.arcs[k][j]<dist[j])
{
dist[j] = dist[k]+G.arcs[k][j]; //更新权值
path[j] = k; //将k加入最短路径
}
}
}
cout<<"顶点"<<G.vertex[v0]<<"到各顶点的最短路径为:[(终点 <- 源点)倒序输出]"<<endl;
for (int i = 1; i < G.vexnum; i++)
{
if(final[i] == 1) //若顶点i在终点集合U中
{
k = i;
while(k!=v0) //顶点序列不与源点相同
{
j = k; //由终点向前追溯
cout<<"<- "<<G.vertex[k]; //输出经过的顶点
k = path[j]; //上一个顶点
}
cout<<"<- "<<G.vertex[k]<<endl; //源点
cout<<"最短路径长度为:";
cout<<dist[i]<<endl;
}else{
cout<<G.vertex[v0]<<"->"<<G.vertex[i]<<":无路径"<<endl;
}
}
}
/*
a b 50
a c 10
a e 45
b c 15
b e 10
c a 20
c d 15
d b 20
d e 35
e d 30
f d 3
*/
单源最短路径----Dijkstra算法
最新推荐文章于 2022-05-27 11:46:12 发布