Dijkstra算法
函数实现
template<class EdgeType>
void Dijkstra(AdjGraph<EdgeType> &G, int s, EdgeType D[], int Path[])//参数:G图引用,
//s源点,
//D是最短路径长度,
//Path[i]为路径上i的前驱顶点编号
{
int n = G.vertexNum;
int i, j;
for (i = 0; i<n; i++)
{
G.Mark[i] = 0; //图标记
D[i] = INFINITY;
Path[i] = -1;//标记此时不存在s到i的路径
}
G.Mark[s] = 1;//把源点的先处理
D[s] = 0;
Path[s] = s;
for (i = 0; i<n; i++)//找到一条最短特殊路径,即min{D[j]|G.Mark[j]==0,0<=j<n}
{
EdgeType min = AFFINITY; //第一次循环肯定是s本身最短
// cout << "第" << i << "次循环"<< endl;
int k = 0;
for (j = 0; j<n; j++)
{
if (G.Mark[j] == 0 && min>D[j])
{
min = D[j];
k = j;
}
}
//已确定从s到k的最短路径
G.Mark[k] = 1;//更新已确定最短特殊路径的点
for (Edge<EdgeType> e = G.FirstEdge(k); G.IsEdge(e); e = G.NextEdge(e))
{
int endVertex = e.end;
if (G.Mark[endVertex] == 0 && D[endVertex] > (D[k] + e.weight))
{//更新到endVertex的最短特殊路径
D[endVertex] = D[k] + e.weight;
Path[endVertex] = k;
}
}
}
}
测试
AdjGraph<int> a(6);//图的构造函数就不贴了
a.setEdge(0, 1, 12);
a.setEdge(0, 2, 10);
a.setEdge(0, 4, 30);
a.setEdge(0, 5, 100);
a.setEdge(1, 2, 5);
a.setEdge(2, 3, 50);
a.setEdge(3, 5, 10);
a.setEdge(4, 3, 20);
a.setEdge(4, 5, 60);
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
cout << a.matrix[i][j] << " ";
}
cout << endl;
}
int D[6],Path[6];
Dijkstra(a, 0, D, Path);
cout << "D[i]:";
for (int i = 0; i < 6; i++)
{
cout << D[i] << " ";
}
cout << endl<<"Path[i]:";
for (int i = 0; i < 6; i++)
{
cout << Path[i] << " ";
}
cout << endl;
for (int i = 0; i < 6; i++)
{
int j=i;
cout << "顶点" << i << ":";
while (j != 0)
{
cout << Path[j] << " ";
j = Path[j];
}
cout << endl;
}
cout << endl;