单源最短路径(图的邻接矩阵)

来源:互联网 发布:淘宝网店水印在线制作 编辑:程序博客网 时间:2024/06/07 06:16
/*********************************************************************************单源最短路径问题(图的邻接矩阵)**某一地区的一个公路网,给定了该网内的n个城市以及这些城市之间的相通公路的距离,能**否找到城市A到城市B之间的一条距离最近的通路呢?**将城市用顶点表示,城市间的公路用边表示,公路的长度作为边的权值。**在网图中,求点A到点B的所有路径中,边的权值之和最短的那一条路径,即最短路径。*********************************************************************************/#include<iostream>#define MaxVertexNum  30#define INFINITY  200using namespace std;typedef int VertexType;typedef struct{VertexType vertexs[MaxVertexNum];int arcs[MaxVertexNum][MaxVertexNum];int vertexNum,edgeNum,weight;}MGraph;int P[MaxVertexNum];int D[MaxVertexNum];void Create_MGraph(MGraph * G);/*创建图*/void ShortestPath_DiJ(MGraph * G,int v0,int P[],int D[]);/*迪杰斯特拉算法*/void Print_ShortestPath(MGraph * G,int v0,int P[],int D[]);/*显示从顶点u到其余顶点的最短路径及距离*/int main(){MGraph * G=(MGraph *)malloc(sizeof(MGraph));Create_MGraph(G);VertexType v0=G->vertexs[0];ShortestPath_DiJ(G,v0,P,D);Print_ShortestPath(G,v0,P,D);return 0;}/*创建图*/void Create_MGraph(MGraph * G){int i,j,k;cout<<"请输入图的顶点数和边数:";cin>>G->vertexNum>>G->edgeNum;cout<<"输入"<<G->vertexNum<<"个顶点的表示形式:";for(i=0;i<G->vertexNum;i++)cin>>G->vertexs[i];/*顶点是字符还是数字*/for(i=0;i<G->vertexNum;i++){for(j=0;j<G->vertexNum;j++){G->arcs[i][j]=INFINITY;}}VertexType v1,v2;int weight;for(k=0;k<G->edgeNum;k++){cout<<"读入边(Vi,Vj)起点和终点对应的序号:";cin>>v1>>v2>>weight;for(i=0;v1!=G->vertexs[i];i++);for(j=0;v2!=G->vertexs[j];j++);G->arcs[i][j]=weight;}}/*迪杰斯特拉算法*/void ShortestPath_DiJ(MGraph * G,int v0,int P[],int D[]){int min;int final[MaxVertexNum];for(int v=0;v<=G->vertexNum-1;v++){final[v]=false;D[v]=G->arcs[v0][v];P[v]=-1;if(D[v]<INFINITY)P[v]=v0;}D[v0]=0;final[v0]=true;for(int i=1;i<=G->vertexNum;i++){v=-1;min=INFINITY;for(int w=0;w<=G->vertexNum-1;w++){if((!final[w])&&D[w]<min){v=w;min=D[w];}}if(v==-1)break;final[v]=true;for(w=0;w<=G->vertexNum-1;w++){if((!final[w])&&(min+G->arcs[v][w]<D[w])){D[w]=min+G->arcs[v][w];P[w]=v;}}}}/*显示从顶点u到其余顶点的最短路径及距离*/void Print_ShortestPath(MGraph * G,int v0,int P[],int D[]){int i;cout<<"从"<<v0<<"出发的最短路径为:\n";for(int v=0;v<=G->vertexNum-1;v++){if(P[v]==-1)continue;cout<<D[v]<<"  ";cout<<v<<"<-";i=v;while(P[i] != -1){if(P[i]==v0)cout<<P[i]<<endl;elsecout<<P[i]<<"<-";i=P[i];}}}

1 0