//头文件
#include <iostream>
const int maxint=101;
template <typename Type,int x,int y>
void Dijkstra(int n,int v,Type dist[],int prev[],Type (&c)[x][y])
{//单源最短路径的Dijkstra算法
bool s[maxint];
for (int i=1;i<=n;i++)
{
dist[i]=c[v][i];
s[i]=false;
if (dist[i]=maxint)
{
prev[i]=0;
}
else
{
prev[i]=v;
}
}
dist[v]=0;
s[v]=true;
for (int i=1;i<n;i++)
{
int temp =maxint;
int u=v;
for (int j=1;j<=n;j++)
{
if ((!s[j])&&(dist[j]<temp))
{
u=j;
temp=dist[j];
}
}
s[u]=true;
for (int j=1;j<=n;j++)
{
if ((!s[j])&&(c[u][j]<maxint))
{
Type newdist=dist[u]+c[u][j];
if (newdist<dist[j])
{
dist[j]=newdist;
prev[j]=u;
}
}
}
}
}
//主函数所在文件
// Dijkstra.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "Dijkstra.h"
int _tmain(int argc, _TCHAR* argv[])
{
const int n=5;
int* dist=new int[n+1];
int* prev=new int[n+1];
int c[n+1][n+1]={{maxint,maxint,maxint,maxint,maxint,maxint},{maxint,maxint,10,maxint,30,100},{maxint,maxint,maxint,50,maxint,maxint},{maxint,maxint,maxint,maxint,maxint,10},{maxint,maxint,maxint,20,maxint,60},{maxint,maxint,maxint,maxint,maxint,maxint}};
Dijkstra(n,1,dist,prev,c);
//int a[2][2]={{1,2},{1,2}};
for (int i=2;i<=n;i++)
{
std::wcout<<"1到"<<i<<"的最短路长为"<<dist[i]<<std::endl;
std::wcout<<"路径为:";
for (int j=i;j>=2;j--)
{
std::cout<<prev[j]<<" ";
}
std::cout<<std::endl;
}
return 0;
}