#include<iostream>
#include<stdio.h>
#include<malloc.h>
#define INF 32767
#define MAXV 5
using namespace std;
typedef char InfoType;
typedef struct
{
int no;
InfoType info;
}VertexType;
typedef struct
{
int edges[MAXV][MAXV];
int n,e;
VertexType vexs[MAXV];
}MatGraph;
void CreateMat(MatGraph &g,int A[MAXV][MAXV],int n,int e)
{
int i,j;
g.n=n;g.e=e;
for(i=0;i<g.n;i++)
{
for(j=0;j<g.n;j++)
{
g.edges[i][j]=A[i][j];
}
}
}
void DispMat(MatGraph g)
{
int i,j;
for(i=0;i<g.n;i++)
{
for(j=0;j<g.n;j++)
{
if(g.edges[i][j]!=INF)
cout<<" "<<g.edges[i][j]<<" ";
else
cout<<" "<<"…";
}
cout<<endl;
}
}
void Dijkstra(int n,int u,float dist[],int p[],int C[5][5])
{
bool s[n];
int i,j;
for(i=0;i<n;i++)
{
dist[i]=C[u][i];
s[i]=false;
if(dist[i]==INF) p[i]=-1;
else p[i]=u;
}
dist[u]=0;
s[u]=true;
for(i=0;i<n;i++)
{
float temp=INF;
int t=u;
for(j=0;j<n;j++)
{
if((!s[j])&&(dist[j]<temp))
{
t=j;
temp=dist[j];
}
}
if(t==u) break;
s[t]=true;
for(j=0;j<n;j++)
{
if((!s[j])&&C[t][j]<INF)
{
if(dist[j]>(dist[t]+C[t][j]))
{
dist[j]=dist[t]+C[t][j];
p[j]=t;
}
}
}
}
cout<<"源点1到2-5的最短路径分别为:";
for(i=1;i<n;i++)
{
cout<<dist[i]<<" ";
}
cout<<endl;
}
int main()
{
MatGraph g;
int A[MAXV][MAXV]=
{
{0,10,INF,30,100},{INF,0,50,INF,INF},{INF,INF,0,INF,10},
{INF,INF,20,0,60},{INF,INF,INF,INF,0}
};
int n=5,e=7;
int visited[5];
for(int i=0;i<5;i++)
visited[i]=0;
CreateMat(g,A,n,e);
cout<<"邻接矩阵为:"<<endl;
DispMat(g);
float dist[4]={0,0,0,0};
int p[4]={0,0,0,0};
Dijkstra(n,0,dist,p,A);
return 0;
}
仅作留档。