原理直接百度,这里只给出c++实现
#include <iostream>
using namespace std;
#define MAXVEX 6
#define INF 10000
void Dijkstra(int cost[][MAXVEX], int numsOfNode, int sourceNode);
void Folyed( int cost[][MAXVEX], int numsOfNode);
void main()
{
int cost[][MAXVEX]=
{
{0,50,10,INF,INF,INF},
{INF,0,15,50,10,INF},
{20,INF,0,15,INF,INF},
{INF,20,INF,0,35,INF},
{INF,INF,INF,30,0,INF},
{INF,INF,INF,3,INF,0}
};
//Dijkstra(cost,MAXVEX,1);
//cout<<endl;
/*
//每队顶点之间的最短距离,调用MAXVEX次Dijkstra
for (int i = 0; i < MAXVEX ; i++ )
{
cout<<"The source is:"<<i<<endl;
Dijkstra(cost,MAXVEX,i);
cout<<endl;
}
*/
Folyed(cost,MAXVEX);
cout<<endl;
}
/*
// Dijkstra是指单源最短路径,即固定一个顶点,求其分别到其他所有顶点的最短路径
void Dijkstra(int cost[][MAXVEX], int numsOfNode, int sourceNode)
{
int dist[MAXVEX]; //dist[]中存放源结点到其他结点的最短路径
int path[MAXVEX]; // path[]中存放最短路径的中当前结点的前一个结点,可以用来求解路径的长度
int s[MAXVEX]; //s[i]中存放0或1,0表示未找到源结点到节点Vi的最短路径,1表示已找到
for (int i = 0; i < numsOfNode; i++)
{
dist[i] = cost[sourceNode][i];
s[i]=0;
if ( cost[sourceNode][i] < INF )
path[i] = sourceNode;
else
path[i] = -1;
}
s[sourceNode] = 1; //源结点的标号放入s中
path[sourceNode] = 0;
for ( int i = 0; i < numsOfNode; i++ )
{
int mindis = INF;
int sign = -1;
for ( int j =0; j < numsOfNode; j++ ) //选出不在s中,且具有最小距离的顶点sign
if( s[j] == 0 && dist[j] < mindis )
{
sign = j;
mindis = dist[j];
}
if( sign != -1)
{
s[sign] = 1; //将sign加入到s中
for( int j = 0; j < numsOfNode; j++ ) //修改不在s中结点的距离
if( s[j] == 0)
if( cost[sign][j] < INF && dist[sign] + cost[sign][j] < dist[j] )
{
dist[j] = dist[sign] + cost[sign][j];
path[j] = sign;
}
}
}
//cout<<endl;
//cout<<"The Dijkstra as follow:"<<endl;
for ( int i = 0; i<numsOfNode; i++)
{
if( i != sourceNode )
{
cout<<sourceNode<<"->"<<i<<":";
if ( s[i] == 1)
{
cout<<"The length of path is: "<<dist[i];
int pre = i;
cout<<" The Reverse Path is: ";
while( pre != sourceNode )
{
cout<<pre<<",";
pre = path[pre];
}
cout<<pre<<endl;
}
else
cout<<" The path is not exis!"<<endl;
}
}
}
*/
void Folyed( int cost[][MAXVEX], int numsOfNode)
{
int dist[MAXVEX][MAXVEX],path[MAXVEX][MAXVEX];
for(int i = 0; i < MAXVEX; i++)
{
for (int j = 0; j < MAXVEX; j++)
{
dist[i][j] = cost[i][j];
path[i][j] = -1;
}
}
for (int k = 0; k < MAXVEX; k++)
{
for(int i = 0; i < MAXVEX; i++)
{
for (int j = 0; j < MAXVEX; j++)
{
if ( dist[i][j] > dist[i][k] + dist[k][j])
{
dist[i][j] = dist[i][k] + dist[k][j];
path[i][j] = k;
}
}
}
}
cout<<endl;
cout<< "The Folyed as follow:"<<endl;
cout<<endl;
for(int i = 0; i < MAXVEX; i++)
{
for (int j = 0; j < MAXVEX; j++)
{
if(i != j)
{
cout<<i<<"->"<<j<<",";
if (dist[i][j] == INF)
cout<<"The path is not exis"<<endl;
else
{
cout<<" The length of path is:"<<dist[i][j]<<", ";
cout<<"The path is: "<<i<<",";
int pre = path[i][j];
while( pre != -1 )
{
cout<<pre<<",";
pre = path[pre][j];
}
cout<<j<<endl;
}
}
}
cout<<endl;
}
}
运行结果:
Dijkstra:
Floyed: