简体   繁体   English

Dijkstra算法实现中的错误

[英]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. 我试图用邻接表来尝试Dijkstra,我不知道为什么我的测试用例不及格。

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, 输入示例:(xyw),1 2 3,1 3 4,1 4 5,3 5 101,

Source is 1. 来源为1。

Output: 3 4 5 5 输出:3 4 5 5

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

Source is 1. 来源为1。

Output: 24 3 15 输出: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 . 让我们用v表示访问数组,用dist表示最佳距离数组。

In this statement: 在此语句中:

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

You need to be using dist instead of v . 您需要使用dist而不是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. 否则,将其标记为已访问并执行其余逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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