Dijkstra算法的基本思想是:每次找到离源点最近的一个顶点,然后以该顶点为中心进行扩展,最终得到源点到其余所有点的最短路径。具体基本步骤如下:
1.将所有的顶点分为两部分:已知最短路径的顶点集合P和未知最短路径的顶点集合Q。最开始,已知最短路径的顶点集合P中只有一个源点一个顶点。我们这里用一个book数组来记录哪些店在集合P中。例如对于某个顶点i,如果book[i]为1则表示这个顶点在集合P中,如果book[I]为0则表示这个顶点在集合Q中。
2.设置源点s到自己的最短路径为0即dis[s]=0。若存在有源点能直接到达的顶点i,则把这个dis[i]设为dis[s,i]。同时把所有其他(源点不能直接到达的)顶点的最短路径设为无限大inf=100000000。
3.在集合Q的所有顶点中选择一个离源点最近的顶点u(即dis[u]最小)加入到集合P。并考察所有以点u为起点的边,对每一条边进行松弛操作。例如存在一条从u到v的边,那么可以通过将边u=>v添加到尾部来拓展一条从s到v的路径,这条路径的长度是dis[u]+e[u][v]。如果这个值比目前已知的dis[v]的值要小,我们可以用新值来替代当前dis[v]中的值。
4.重复第三步,如果集合Q为空,算法结束。最终dis数组中的值就是源点到所有顶点的最短路径。
C#代码:(路径存在list path中)
class Program
{
public static List<int> path = new List<int>();//存储路径
public static int n = 6;
public static int inf = 100000000;//无路段--------
public static int[,] cost = new int[n, n];
public static int[] f;
public static int[] t;
public static double[] c;
static void Main(string[] args)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i != j)
{
cost[i, j] = inf;
}
else
{
cost[i, j] = 0;
}
}
}
ReadNode1(@"cost.txt");
ShortestPath();
//ShortestPath1();
//BellmanFord();
Console.ReadKey();
}
static void ReadNode1(string DataPath)//读取邻接表(如:1 2 1 )结点1到结点2距离为1:
{
if (!File.Exists(DataPath))
{
Console.WriteLine("{0} does not exist!", DataPath);
return;
}
StreamReader sr = File.OpenText(DataPath);
String input;
String[] Data = null;
int index = 0;
while ((input = sr.ReadLine()) != null)
{
if (input == "") continue;
Data = input.Split('\t');
cost[int.Parse(Data[0]) - 1, int.Parse(Data[1]) - 1] = int.Parse(Data[2]);
index++;
}
sr.Close();
}
static void ShortestPath()
{
int g = 1;//出发点
int h = 4;//终点
int[] book = new int[n]; //book[i]=0表示此结点最短路未确定,为1表示已确定
//double[,] cost = Matrix.LoadData("cost1.txt", '\t');//路之间的权值,即距离
double[] distance = new double[n];//出发点到各点最短距离
int[] last1 = new int[n];//存储最短路径,每个结点的上一个结点
double min;
int u = 0;
//初始化distance,这是出发点到各点的初始距离
for (int i = 0; i < n; i++)
{
//distance[i] = cost[0, i];
distance[i] = cost[g, i];
}
//初始化出发点的book
for (int i = 0; i < n; i++)
{
last1[i] = g;
}
last1[g] = -1;
book[g] = 1;
//核心算法
for (int i = 0; i < n - 1; i++)
{
min = inf;
//找到离g号结点最近的点
for (int j = 0; j < n; j++)
{
if (book[j] == 0 && distance[j] < min && distance[j] != 0)
{
min = distance[j];
u = j;
}
}
book[u] = 1;
for (int v = 0; v < n; v++)
{
if (cost[u, v] < inf && cost[u, v] != 0)
{
if (distance[v] > distance[u] + cost[u, v])
{
distance[v] = distance[u] + cost[u, v];
last1[v] = u;
}
}
}
}
Console.WriteLine("{0}点到各节点最短距离:", g);
for (int i = 0; i < n; i++)
{
if (distance[i] < inf)
{
Console.Write("{0} ", distance[i]);
}
else
{
Console.Write("无法到达");
}
}
Console.WriteLine();
int k = h;
path.Add(k);
while (k != g)
{
if (distance[k] >= inf)
{
Console.WriteLine("无法到达该节点");
break;
}
k = last1[k];
path.Add(k);
}
path.Reverse();
Console.WriteLine("到终点最短路径");
foreach (int i in path)
{
Console.Write(i + 1 + " ");
}
Console.WriteLine();
Console.WriteLine();
}