#include<iostream>
using namespace std;
#define Max 1000.0
void dijkstra(int v,float a[6][6],float* dist,int* prev,int Num)
{
int n = Num-1;
if(v<1||v>n) return;
int s[6+1];
///初始化
for(int i = 1;i<=n;i++)
{
dist[i] = a[v][i];
s[i] = 0;
if(dist[i] == Max)prev[i] = 0;
else prev[i] = v;
}
dist[v] = 0;
s[v] = 1;
for(int i = 1;i<n;i++)
{
float temp = Max;
int u = v;
for(int j = 1;j<=n;j++){
if((s[j] == 0)&&(dist[j]<temp)){
u = j;
temp = dist[j];
}
}
s[u] = 1;
for(int j = 1;j<=n;j++)
if((s[j] == 0)&&(a[u][j]<Max)){
float newdist = dist[u]+a[u][j];
if(newdist < dist[j]){
//dist[j]减少
dist[j] = newdist;
prev[j] = u;
}
}
}
///相关输出语句
cout<<"源点到其它点的最短距离分别为:";
for(int i = 1;i<=n;i++)
cout<<dist[i]<<" ";
cout<<endl<<"源点到顶点5的最短路径为 ";
int path[5],j = 0;
for(int i= 5;1<i&&i<=n;j++)
{
path[j] = prev[i];
i = prev[i];
}
for(int i = 0;i<j;i++)
cout<<path[i]<<" ";
}
int main()
{
float a[6][6] = { ///由于Dijkstra算法中计数因子从1 开始,所以初始化数组要多一行一列
{Max},
{Max,Max,10,Max,30,100},
{Max,10,Max,50,Max,Max},
{Max,Max,50,Max,20,10},
{Max,30,Max,20,Max,60},
{Max,100,Max,10,60,Max}
};
float dist[6];
int prev[6];
int n = 6;
int v = 1;
dijkstra(v,a,dist,prev,n);
}
关于算法的理解和证明,参考《算法设计与分析》,王晓东著。
关于代码理解,建议手动模拟。(由于数据的特殊性,手动模拟相当简单而且易懂)