【问题标题】:Infinite loop in my BFS function我的 BFS 函数中的无限循环
【发布时间】:2015-11-13 18:30:04
【问题描述】:

我正在尝试在 C++ 中实现 BFS 算法以查找每个节点与源顶点的距离(例如 0),但我的函数中似乎存在无限循环。经过一些调试后,我发现所有节点都被访问了,但我的队列永远不会为空。这是为什么呢?

#include <bits/stdc++.h>

using namespace std;

int d[1000];
int visited[1000];
vector <int> adj[1000];

queue<int> que;

void bfs(int source)
    {
        d[source]=0;
        visited[source]=1;
        que.push(source);
        while(!que.empty())
        {
            int current = que.front();
            que.pop();
            for (int i=0;i<adj[current].size();i++)
                {
                    int v=adj[current][i];
                    if(visited[v]!=1);
                    { 
                        visited[v]=1;
                        d[v]=d[current]+1;
                        que.push(v);
                    }
                }
        }
    }
int main(){
    int E,start,end,n;
    cin >> n >> E;
    for (int i=0;i<n;i++)
            d[i]=-1;
    for (int i=0;i<n;i++)
            visited[i]=0;
    for (int i=0;i<E;i++)
        {
            cin >> start >> end;
            adj[start].push_back(end);
            adj[end].push_back(start);
        }
    bfs(0);
    for (int i=0;i<n;i++)
        cout << "d" << i << "= " << d[i] << endl;
    return 0;
}

【问题讨论】:

    标签: c++ algorithm graph shortest-path breadth-first-search


    【解决方案1】:

    我看到的唯一错误是 ::

    if(visited[v]!=1);

    您只需要删除分号! :D

    【讨论】:

    • 我花了 2 个小时试图找出问题所在:D。谢谢你!你让我开心。
    • @FoxyZ 你可以考虑在退出循环之前添加一个条件,如果你的所有节点都被访问过,以防你的图没有连接!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    相关资源
    最近更新 更多