Dijkstra算法是典型的最短路径路由算法,用来计算一个节点到其他所有可能节点的最短路径,具体算法流程介绍等可以谷歌之。
这里贴一份C++代码,图是用邻接矩阵来表示的。
#include "stdafx.h"
#include <iostream>
using namespace std;
namespace Dijkstra
{
const int MAX = 100;
int c[MAX][MAX];
int distance[MAX]; //当前节点到源节点的最短路径长度
int previous[MAX]; //当前节点的前一个节点
void dijkstra(int n, int v, int distance[], int previous[], int c[][MAX])
{
bool s[MAX]; //是否把节点加入集合中
for (int i = 1; i <= n; i++)
{
s[i] = 0; //始终都未用过该点
distance[i] = c[v][i];
s[i] = 0;
if (distance[i] == INT_MAX)
previous[i] = 0;
else previous[i] = v;
}
distance[v] = 0;
s[v] = 1;
//依次将未放入S集合的节点取distance最小值放入到集合S中
for (int i = 2; i <= n; i++)
{
int u = v;
//找出当前未使用的点j的distance[j]的最小值
for (int j = 1; j <= n; j++)
{
int temp = INT_MAX;
int u;
for (int j = 1; j <= n; j++)
if (!s[j] && distance[j] < temp)
{
u = j; //记录T中到源节点距离最小的点
temp = distance[j];
}
s[u] = 1;
for (int j = 1; j <= n; j++)
{
if (!s[j] && c[u][j] < INT_MAX)
{
if (distance[u] + c[u][j] < distance[j])
{
distance[j] = distance[u] + c[u][j];
previous[j] = u;
}
}
}
}
}
}
void printPath(int* previous,int v,int u)
{
int pathArray[MAX];
int temp;
int i = 0;
temp = previous[u];
while (temp != v)
{
pathArray[i++] = temp;
temp = previous[temp];
}
pathArray[i] = v;
for (int j = i; j >= 0; j--)
{
cout << pathArray[j];
cout << "->";
}
cout<<u<<endl;
}
void test()
{
for (int i = 0; i < MAX; i++)
for (int j = 0; j < MAX; j++)
c[i][j] = INT_MAX;
c[1][2] = 10;
c[1][4] = 30;
c[1][5] = 100;
c[2][3] = 50;
c[3][5] = 10;
c[4][3] = 20;
c[4][5] = 60;
dijkstra(5, 1, distance, previous, c);
printPath(previous, 1, 2);
printPath(previous, 1, 3);
printPath(previous, 1, 4);
printPath(previous, 1, 5);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Dijkstra::test();
return 0;
}
运行结果: