数据结构之C++实现最短路径迪杰特斯拉(dijkstra)算法.md
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include "sys/io.h"
using namespace std;
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXEDGE 20
#define MAXVEX 20
#define GRAPH_INFINITY 65535
typedef int Status;
class MGraph
{
public:
MGraph();
void CreatMGraph(void);
void ShortestPath_Dijkstra(int v0);
void show(void);
public:
int vexs[MAXVEX];
int arc[MAXVEX][MAXVEX];
int numVertexes,numEdges;
int Patharc[MAXVEX];
int ShortPathTable[MAXVEX];
};
MGraph::MGraph()
{
for (int i = 0; i < MAXVEX; i++)
{
vexs[i]=i;
}
for (int i = 0; i < MAXVEX; i++)
{
for (int j = 0; j < MAXVEX; j++)
{
if (i==j)
arc[i][j]=0;
else
arc[i][j] = arc[j][i] = GRAPH_INFINITY;
}
}
}
void MGraph::CreatMGraph(void)
{
int i, j;
numEdges=16;
numVertexes=9;
arc[0][1]=1;
arc[0][2]=5;
arc[1][2]=3;
arc[1][3]=7;
arc[1][4]=5;
arc[2][4]=1;
arc[2][5]=7;
arc[3][4]=2;
arc[3][6]=3;
arc[4][5]=3;
arc[4][6]=6;
arc[4][7]=9;
arc[5][7]=5;
arc[6][7]=2;
arc[6][8]=7;
arc[7][8]=4;
for(i = 0; i < numVertexes; i++)
{
for(j = i; j < numVertexes; j++)
{
arc[j][i] =arc[i][j];
}
}
}
void MGraph::ShortestPath_Dijkstra(int v0)
{
int v,w,k,min;
int final[MAXVEX];
for(v=0; v<numVertexes; v++)
{
final[v] = 0;
ShortPathTable[v] = arc[v0][v];
Patharc[v] = -1;
}
ShortPathTable[v0] = 0;
final[v0] = 1;
for(v=1; v<numVertexes; v++)
{
min=GRAPH_INFINITY;
for(w=0; w<numVertexes; w++)
{
if(!final[w] && ShortPathTable[w]<min)
{
k=w;
min = ShortPathTable[w];
}
}
final[k] = 1;
for(w=0; w<numVertexes; w++)
{
if(!final[w] && (min+arc[k][w]<ShortPathTable[w]))
{
ShortPathTable[w] = min + arc[k][w];
Patharc[w]=k;
}
}
}
}
void MGraph::show(void)
{
cout<<"vexs is ";
for(int i=0;i<numVertexes;i++)
{
cout<<vexs[i]<<" ";
}
cout<<endl<<"arc is "<<endl;
for(int i=0;i<numVertexes;i++)
{
for(int j=0;j<numVertexes;j++)
{
cout<<arc[i][j]<<" ";
}
cout<<endl;
}
}
int main()
{
int i,j,v0;
MGraph *G=new MGraph;
v0=0;
G->CreatMGraph();
G->show();
G->ShortestPath_Dijkstra(v0);
cout<<"最短路径倒序如下:"<<endl;
for(i=1;i<G->numVertexes;++i)
{
cout<< "v"<<v0<<" - v"<<i<<" : ";
j=i;
while(G->Patharc[j]!=-1)
{
cout<<G->Patharc[j]<<" ";
j=G->Patharc[j];
}
cout<<endl;
}
cout<<endl<<"源点到各顶点的最短路径长度为:"<<endl;
for(i=1;i<G->numVertexes;++i)
cout<<"v"<<G->vexs[0]<<" - v"<<G->vexs[i]<<" : "<<G->ShortPathTable[i]<<endl;
delete G;
return 0;
}
|