void shortestPaths(int sourceVertex,T* distanceFromSource, int* predecessor)
{
//predecessor[i]保存从源定点到达顶点i的路径中前面的那个顶点
// Find shortest paths from sourceVertex.
// Return shortest distances in distanceFromSource.
// Return predecessor information in predecessor.
if (sourceVertex < 1 || sourceVertex > n)
throw illegalParameterValue("Invalid source vertex");
if (!weighted())
throw undefinedMethod
("adjacencyWDigraph::shortestPaths() not defined for unweighted graphs");
//使用无序链表保存可到达的顶点
graphChain<int> newReachableVertices;
// initialize
//所有邻接于源顶点的顶点i,令predecessor[i] = sourceVertex
//对所有其他顶点predecessor[i] = -1且predecessor[sourceVertex] = 0
//创建表newReachableVertices存储所有predecessor[i]>0的顶点(即邻接于源顶点的点)
for (int i = 1; i <= n; i++)
{
distanceFromSource[i] = a[sourceVertex][i];
if (distanceFromSource[i] == noEdge)
predecessor[i] = -1;
else
{
predecessor[i] = sourceVertex;
newReachableVertices.insert(0, i);
}
}
distanceFromSource[sourceVertex] = 0;
predecessor[sourceVertex] = 0; // source vertex has no predecessor
// update distanceFromSource and predecessor
while (!newReachableVertices.empty())
{// more paths exist
// find unreached vertex v with least distanceFromSource
chain<int>::iterator iNewReachableVertices
= newReachableVertices.begin();
chain<int>::iterator theEnd = newReachableVertices.end();
int v = *iNewReachableVertices;
iNewReachableVertices++;
//寻找表中路径最短的边
while (iNewReachableVertices != theEnd)
{
int w = *iNewReachableVertices;
iNewReachableVertices++;
if (distanceFromSource[w] < distanceFromSource[v])
v = w;
}
// next shortest path is to vertex v, delete v from
// newReachableVertices and update distanceFromSource
newReachableVertices.eraseElement(v);
for (int j = 1; j <= n; j++)
{
//发现新路径时,更新最短路径。
if (a[v][j] != noEdge && (predecessor[j] == -1 ||
distanceFromSource[j] > distanceFromSource[v] + a[v][j]))
{
// distanceFromSource[j] decreases
distanceFromSource[j] = distanceFromSource[v] + a[v][j];
// add j to newReachableVertices
if (predecessor[j] == -1)
// not reached before 没在表中时要加入Reach
newReachableVertices.insert(0, j);
predecessor[j] = v;//保存路径
}
}
}
}
dijkstra算法C++实现(最短路径)
原文作者:Dijkstra算法
原文地址: https://blog.csdn.net/lbwo001/article/details/79955643
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/lbwo001/article/details/79955643
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。