Dijkstra算法之一

#include <iostream>        //单源顶点最短路径:迪杰斯特拉(Dijkstra)算法
using namespace std;

const int MaxWeight=100000; //MaxWeight表示无穷大
int Vertex,edge[1000][1000],distD[1000],i,j;
void init()
{
for(i=1;i<=Vertex;i++) //结点坐标都是从1开始的
for(j=1;j<=Vertex;j++)
{
if(i==j)
edge[i][j]
=0;
else
edge[i][j]
=MaxWeight;
}
}
void Dijstra(int v) //从源点v到其余各顶点的最短路径长度
{
int min,u,S[1000],pathD[1000];
for(i=1;i<=Vertex;i++)
{
distD[i]
=edge[v][i];S[i]=0;
if(i!=v&&distD[i]<MaxWeight)
pathD[i]
=v;
else
pathD[i]
=-1;
}
S[v]
=1;
for(i=1;i<Vertex;i++) //对剩下的(vertex-1)个顶点计算最短路径
{
min
=MaxWeight;
for(j=1;j<=Vertex;j++)
if(!S[j]&&distD[j]<min)
{
u
=j;min=distD[j];
}
S[u]
=1;
//不用另外判断edge[u][j]<MaxWeight ,但如果MaxWeight初始化太大,则distD[u]+edge[u][j]有可能会超int范围,
//要强制转换为long long : (long long)distD[u]+edge[u][j]<(long long)distD[j]
for(j=1;j<=Vertex;j++)
if(!S[j]&&distD[u]+edge[u][j]<distD[j])
{
distD[j]
=distD[u]+edge[u][j];pathD[j]=u;
}
}
for(i=1;i<=Vertex;i++)
if(i!=v)cout<<"从顶点"<<v<<" 到顶点"<<i<<" 的最短路径是: "<<distD[i]<<endl;
}
int main()
{

return 0;
}

  

posted on 2011-07-17 01:43  sysu_mjc  阅读(189)  评论(0编辑  收藏  举报

导航