dijkstra算法不正确的条件

时间:2017-11-26 09:22:52

标签: c++ algorithm conditional dijkstra

我正在研究使用优先级队列的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;

这是顶点类

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函数相关的代码,但如果有什么不清楚我可以添加更多。

1 个答案:

答案 0 :(得分:0)

您的算法实施不正确。

从队列中struct X { int a; }; void fun(struct X *b) { struct X c; c=*b; printf("%d %d",c,c.a); } int main() { struct X d; int p; p=20; printf("Hello World"); fun(&p); return 0; } 顶点pop()之后(因为它与源的距离最低),您应该只检查可以从u直接到达的顶点(即从u到该顶点存在一条边。)

您当前的实现似乎是循环遍历所有顶点,无论它们是否可以从u直接到达,并且可能因此,您正在做一些奇怪的距离计算,这是没有意义的。更具体地说,您的实现中的u似乎是荒谬的。

Dijkstra算法背后的关键理念是:

distance_total