简体   繁体   English

我的BFS功能中的无限循环

[英]Infinite loop in my BFS function

I'm trying to implement the BFS algorithm in C++ to find the distance of each node from a source vertex (eg 0), But it seems like there's an infinite loop in my function. 我正在尝试用C ++实现BFS算法来查找每个节点与源顶点的距离(例如0),但似乎我的函数中存在无限循环。 After some debugging I found out that all nodes get visited but my queue never gets empty. 经过一些调试后,我发现所有节点都被访问过,但我的队列永远不会变空。 Why is that? 这是为什么?

#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;
}

The only error I see is :: 我看到的唯一错误是::

if(visited[v]!=1);

A semicolon is all you need to remove!! 你只需要一个分号即可! :D :d

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

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