【问题标题】:Dijkstra's algorithm in c++ infinite loopc++无限循环中的Dijkstra算法
【发布时间】:2016-02-03 15:24:32
【问题描述】:

我试图在 C++ 中实现 Dijkstras 的算法。现在我在调试时遇到了麻烦。在我的代码中某处有一个无限循环。我的图形实现很糟糕。如果您有任何想法我的代码有什么问题,即使它与主要问题无关,请告诉我。

我不需要其他人的代码,我需要它作为我的代码但已修复,以便我可以在代码中找到我的错误并更好地理解它(我只理解我的代码,遗憾的是 c++ 编译器不理解)。

这是我的代码:

#include <iostream>
#include <vector>
#include <limits.h>
#include <queue>
using namespace std;

vector < vector<int> > graf;
int fromnode, tonode;

struct nodeinfo
{
    //this contains info about a node
    bool visited = 0;
    int dis = INT_MAX/2;
};
nodeinfo sample;
vector<nodeinfo> info; // if visited
queue<int> togo;

// dijkstra algorithm
void dijkstra(int currnode)
{
    //visited current node
    info[currnode].visited = 1;
    //go see every node connected to the current one
    for(int i = 0; i < graf[currnode].size(); i ++){
        if (graf[currnode][i] != INT_MAX/2 ) {
            // if visited push to queue and check distance
            if(info[i].visited== 0)
                togo.push(i);
            info[i].dis = max(info[i].dis,info[currnode].dis + graf[currnode][i]);
        }
    }
}


int main()
{
    //input n
    int n;
    cin >> n;

    //declaring variables
    graf.resize(n*2);
    info.resize(n*2);
    vector<int> fillin (100,INT_MAX/2);
    graf.insert(graf.begin(),100,fillin);
    int a,b,c;

    //input in graphinfo[graf[currnode][i
    for(int i = 0; i < n; i ++){
        cin >> a >> b >> c;
        if (graf[a][b] > c)
            graf[a][b] = graf[b][a] = c;
        cout << i << endl;
    }
    // input from witch node to go and where to go and
    cin >> fromnode >> tonode;
    info[fromnode].dis = 0;
    togo.push(fromnode);
    //dijkstra start
    while(!togo.empty()){
        dijkstra(togo.front());
    }
    // output
    cout << info[tonode].dis << endl;
    return 0;
}

在我使用此输入将cout &lt;&lt; "at node " &lt;&lt; currnode &lt;&lt; endl; 放在 dijskstra 函数的开头之后:

卡在节点 1:

【问题讨论】:

  • 你知道如何使用调试器吗?

标签: c++ algorithm dijkstra


【解决方案1】:

你的循环说

while(!togo.empty())

但您永远不会从 togo 中删除任何内容。
你会想在合适的地方pop
(找到一个合适的地方作为练习。)

【讨论】:

  • 哦。 wtf我怎么错过了?谢啦。顺便说一句,我刚刚意识到我的代码正在寻找一个最大值而不是最小路径,谢谢它的工作原理
  • 对修复我的图形实现有一些想法吗?我真的很感激。我的意思是我可以使用超过 100 个节点:graf.insert(graf.begin(),100,fillin);
  • 和其他我无缘无故打出来的sh**
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-06
  • 2020-02-26
  • 2014-12-22
相关资源
最近更新 更多