Dijkstra算法:
首先交代一下用于dijkstra算法的表,与无权最短路径计算相似的,需要一个用于计算的表,表的定义如下:
class Table
{
public string Name; //顶点的名字
public bool Known; //找到最短路径标志
public double Dist; //距离起点的路径值
public Vertex Path; //最短路径中的前一个顶点
public Table()
{
Name = null;
Known = false;
Dist = double.PositiveInfinity;
Path = null;
}
public static int GetIndex(Table[] table,string name)
{
int Index = -1;
for (int i = 0; i < table.Length; i++)
{
if (table[i].Name == name)
{
Index = i;
break;
}
}
return Index;
}
}
<1>S:最短路径已经确定(known=true)的顶点集合,初始化时为{start_vertex}或空集,start_vertex为起点;U:除去S中顶点以外的顶点集合;
<2>用于计算dijkstra的表的初始化时,起点start_vertex的Dist初始化0,其余顶点为无穷大(或者将与起点start_vertex相邻的顶点的Dist初始化为起点与该顶点的权值,不相邻的初始化为无穷大);
<3>从U中选取一个距离起点start_vertex最小的顶点v,把v纳入S中,这个最短距离就是start_vertex到v的最短路径距离;
<4>以顶点v作为中间点,修改U中与顶点v相邻的顶点w距离,若从起点start_vertex经过v到相邻顶点w的距离比原来的距离短,则修改相邻顶点w的距离,修改后的距离值为顶点v的距离值加上v到w的权值;
<5>重复<3>和<4>直到所有的顶点包含在S中。
具体实现代码:
/// <summary>
/// dijkstra算法,有权单源最短路径
/// </summary>
/// <param name="g_matrix"></param>
/// <param name="start_vertex"></param>
/// <returns></returns>
private static Table[] Dijkstra(Graphic_Matrix g_matrix,Vertex start_vertex)
{
Vertex v;
int v_index=0;
double min_dist = 100000;
Queue<Vertex> queue = Queue<Vertex>.CreateQueue(g_matrix.Size);
Table[] table = new Table[g_matrix.Size];
InitTable(g_matrix, start_vertex, table);
for (int n = 0; n < g_matrix.Size;n++)
{
//----------------------------------------------------------------------------------------
min_dist = 100000;
for (int i = 0; i < g_matrix.Size; i++)
{
if (!table[i].Known)
{
if (table[i].Dist < min_dist) //选取距离v1最短路径入队
{
min_dist = table[i].Dist;
v_index = i;
}
}
}
//---------------------------------------------------------------------------------------
v = new Vertex(table[v_index].Name);
table[v_index].Known = true;
for (int i = 0; i < g_matrix.Size; i++)
{
if (g_matrix.AdjacencyMat[v_index, i] != 0) //临近点
{
if (!table[i].Known)
{
if (table[v_index].Dist + g_matrix.AdjacencyMat[v_index, i] < table[i].Dist)
{ //更新该顶点临近点的路径距离
table[i].Dist = table[v_index].Dist + g_matrix.AdjacencyMat[v_index, i];
table[i].Path = v;
}
}
}
}
//---------------------------------------------------------------------------------------
}
return table;
}
对下图进行单源(v1)最短路径查找:
输出结果: