/**********************迪杰斯特拉算法*********************************************/
#include <stdio.h>
#define INFINITY 10000
#define TRUE 1
#define FALSE 0
#define VERTEX_NUM 6
typedef struct Graph
{
char vexs[VERTEX_NUM]; /*顶点*/
int arcs[VERTEX_NUM][VERTEX_NUM]; /*邻接矩阵*/
int vexnum; /*顶点数*/
int arcnum; /*弧数*/
}Graph;
void ShortestPath(Graph g,int v0,int p[][VERTEX_NUM],int d[])
{
/*迪杰斯特拉算法求最短路径,g为图的邻接矩阵,v0为起始顶点,
p[v][w]储存v0到v路径上w的后继顶点(无后继置-1),d[v]为路径v0到v的带权长度*/
int v;
int w;
int min;
int i,j;
int final[VERTEX_NUM]; /*final[v]=TRUE当且仅当v属于S*/
/*初始化数组*/
for (v = 0; v < g.vexnum; v++)
{
final[v] = FALSE;
d[v] = g.arcs[v0][v];
for (w = 0; w < g.vexnum; w++)
{
p[v][w] = -1;
}
if (d[v] < INFINITY)
{
p[v][0] = v0;
p[v][1] = v;
}
}
/*初始化,顶点v0属于S集合*/
d[v0] = 0;
final[v0] = TRUE;
/*循环n-1次求最短路径*/
for (i = 1; i < g.vexnum; i++)
{
min=INFINITY;
for (w = 0; w<g.vexnum; w++)
{
if (!final[w]) /* w属于V-S */
{
if (d[w] < min)
{
/* w顶点离v0更近 */
v=w;
min=d[w];
}
}
}
final[v] = TRUE; /*离v0顶点最近的v加入S集*/
for (w = 0; w<g.vexnum; w++) /*更新当前最短路径及距离*/
{
if (!final[w] && (min+g.arcs[v][w] < d[w]) )
{
/*修改d[w]和p[w] (w属于V-S) */
d[w] = min + g.arcs[v][w];
for (j = 0; p[v][j]> -1 && j < VERTEX_NUM; j++)
{
p[w][j] = p[v][j]; /* p[w]=p[v] */
}
p[w][j] = w; /* p[w]=p[v]+w */
}
}
}
}
void main()
{
int i,
j;
Graph g;
int p[VERTEX_NUM][VERTEX_NUM];
int d[VERTEX_NUM];
int v0;
/*初始化图g*/
g.vexs[0]='A',g.vexs[1]='B',g.vexs[2]='C',g.vexs[3]='D',g.vexs[4]='E',g.vexs[5]='F';
for(i=0;i<VERTEX_NUM;i++)
for(j=0;j<VERTEX_NUM;j++)
g.arcs[i][j]=INFINITY;
g.arcs[0][2]=10,g.arcs[0][4]=30,g.arcs[0][5]=100,g.arcs[1][2]=5,
g.arcs[2][3]=50,g.arcs[3][5]=10,g.arcs[4][3]=20,g.arcs[4][5]=60;
g.vexnum=g.arcnum=VERTEX_NUM;
/*输出图的有关信息*/
for(i=0;i<VERTEX_NUM;i++)
{
printf("%c\t",g.vexs[i]);
for(j=0;j<VERTEX_NUM;j++)
{
printf("%5d ",g.arcs[i][j]);
}
printf("\n");
}
printf("\n");
/*求最短路径*/
v0 = 0;
ShortestPath(g,v0,p,d);
/*输出最短路径*/
for (i = 0; i < g.vexnum; i++)
{
printf("Path %c to %c:\n",g.vexs[v0],g.vexs[i]);
if ( p[i][v0] != -1 ) /*存在路径则输出*/
{
for (j = 0; p[i][j]!=-1; j++)
{
if (j != 0)
printf("→");
printf(" %c",g.vexs[p[i][j]]);
}
printf("\n");
}
printf("Length:%d\n",d[i]);
printf("\n");
}
}
/**********************迪杰斯特拉算法*********************************************/