Dijkstra算法条件不正确

dijkstra algorithm incorrect conditional

本文关键字:不正确 条件 算法 Dijkstra      更新时间:2023-10-16

我正在使用优先队列处理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);
                }
            }
        }
    }
};

这是Graph类

class Graph
{
    vector<Vertex*> _vertices;      // All vertices in the graph (vertex id == index)
    int _last_startingID = -1;

这是顶点类

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函数重新保留的代码,但是如果有什么尚不清楚,我可以添加更多。

您对算法的实现不正确。

从队列中 pop() pertex 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)