我正在研究一个使用优先级队列的dijkstra算法。我已经做了很多研究,我认为我的代码遵循算法,但在比较最短路径时,我无法进入条件
void dijkstra( int startingID ) {
priority_queue<Vertex*, vector<Vertex*>, PathWeightComparer> dijkstra_queue{};
vector<Vertex*> vert;
vert = _vertices;
int n = vert.size();
vector< double > dis(n);
for (int i = 0; i < n; i++)
{
dis[i] = std::numeric_limits< double >::infinity();
}
vert[startingID]->setPathWeight(startingID);
dis[startingID] = 0;
Vertex* temp = vert[startingID];
dijkstra_queue.push(temp);
while (!dijkstra_queue.empty())
{
double dist = dijkstra_queue.top()->getPathWeight();
double u = dijkstra_queue.top()->getId();
dijkstra_queue.pop();
for (auto i : vert)
{
double v = i->getId();
double weight = i->getPathWeight();
double distance_total = dist + weight;
cout << "distance_total " << distance_total << " dis[v] " << dis[v] << endl;
if (distance_total < dis[v]) //PROBLEM
{
dis[v] = distance_total;
Vertex* temp2 = i;
temp2->setPathWeight(dis[v]);
dijkstra_queue.push(temp2);
}
}
}
}
};下面是这个图形类
class Graph
{
vector<Vertex*> _vertices; // All vertices in the graph (vertex id == index)
int _last_startingID = -1;这是vertex类
class Vertex
{
private:
int _id; // ID (key) of given vertice
bool _known = false; // Dijkstra's algorithm "known" flag
Vertex* _path = nullptr; // Dijkstra's algorithm parent vertex pointer
// Weight of path through graph - starts at a true infinity (inf)
double _path_weight = std::numeric_limits<double>::infinity();我试图只包含与dijkstra函数相关的代码,但如果有任何不清楚的地方,我可以添加更多。
发布于 2017-11-29 12:25:18
您的算法实现不正确。
从队列中pop()顶点u之后(因为它与源的距离最小),应该只检查可以直接从u到达的顶点(即存在从u到该顶点的边)。
您当前的实现似乎正在循环遍历所有顶点,而不管它们是否可以直接从u访问,因此,您可能正在对距离计算做一些奇怪的事情,这是没有意义的。更具体地说,在您的实现中使用distance_total似乎是毫无意义的。
Dijkstra算法背后的关键思想是:
dis[u] = must be shortest path from source to u since u was popped.
dis[v] = current_known_distance_to_v
Then, for all v where edge exists from u to v:
IF dis[u] + weight(u, v) < dis[v]:
// going via u is better than the current best known distance to v
dis[v] = dis[u] + weight(u, v)https://stackoverflow.com/questions/47494676
复制相似问题