简体   繁体   中英

Dijkstra algorithm with Adjacency list Undirected Graph

I'm trying to write a method that would find the shortest path length from one vertex to another, using Dijkstra algorithm. But it doesn't give a correct output. Could you give some advice as to where the problem is?

unsigned distDIJKSTRA(unsigned vert1, unsigned vert2)
    {
        vector<Vertex3*> pq;
        Vertex3* v;
        unsigned distance = UINT_MAX;
        for (unsigned i = 0; i < vertices.size(); i++)
        {
            if (vertices[i]->value == vert1)
                v = new Vertex3(vertices[i], 0);
            else 
                v = new Vertex3(vertices[i], distance);
            pq.push_back(v);
        }

        make_heap(pq.begin(), pq.end(), lowerPrior);
        unsigned newDist;
        while (!pq.empty())
        {
            Vertex3* currV = pq.front();

            // If the destination is reached
            if (currV->vert->value == vert2)
                return currV->dist;

            pop_heap(pq.begin(), pq.end(), lowerPrior);
            pq.pop_back();

            // Checking if the route through currV is shorter
            for (unsigned i = 0; i < currV->vert->adjList.size(); i++)
            {
                Vertex3* nextV = nullptr;
                for (unsigned j = 0; j < pq.size(); j++)
                    if (pq[j]->vert == currV->vert->adjList[i]) {
                        nextV = pq[j];
                        break;
                    }
                if (nextV != nullptr)
                {
                    newDist = currV->dist + getWeight(currV->vert, nextV->vert);
                    if (newDist < nextV->dist)
                        nextV->dist = newDist;
                }
                else
                    continue;
            }
            sort_heap(pq.begin(), pq.end(), lowerPrior);    
        }
        return UINT_MAX;
    }

After updating the distances, your vector won't be a heap anymore. Further more, calling sort_heap in itself would also drop the heap property, instead of fixing it. (See http://en.cppreference.com/w/cpp/algorithm/sort_heap ) Call make_heap instead.

Also note the memory leak: you never deallocate the memory allocated for the Vertex3 objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM