简体   繁体   中英

Error in Implementation of Dijkstra's Algorithm

I am trying to attempt Dijkstra's with an Adjacency list, I can't figure out why I'm failing the test cases.

Node * n = list[source].head;
while(n)
{
    q.push(n);
    v[n->b] = n->w;
    n = n->next;
}

while(!q.empty())
{
    n = q.front();
    i = n->b;
    o = list[i].head;
    q.pop();

    while(o)
    {
        if(!v[o->b]) 
        {
            q.push(o);
            v[o->b] = v[i] + o->w;
        } 
        else if(v[o->b] > v[i] + o->w)
        {
            v[o->b] = v[i] + o->w;   
        }
        o = o->next;
    }
}

i = 0;
while(i < vertices)
{
    if(i != node)
        printf("%d ", v[i] ? v[i] : -1);
    i++;
}
cout<<"\n";

I am passing trivial test cases.

Example Input: (xyw), 1 2 3, 1 3 4, 1 4 5, 3 5 101,

Source is 1.

Output: 3 4 5 5

Example 2: 1 2 24 1 4 20 3 1 3 4 3 12

Source is 1.

Output: 24 3 15

However, I am failing the more sophisticated test cases.

It seems you are confusing the two arrays - one for which vertex is already visited, and one for the optimal special distances(ie optimal distance to the vertices found so far). Let's denote the visited array with v and the optimal distance array with dist .

In this statement:

if(v[o->b] > v[i] + o->w)

You need to be using dist instead of v .

After you pop a node you need to check if it is visited. If it is visited, continue on to the next node. Otherwise mark it as visited and execute the remaining logic.

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