Search code examples
c++graph-theorybreadth-first-searchgraph-traversal

Breadth first search stuck in infinite loop


I am trying to implement breadth first search algorithm but due to some reasons it is getting stuck in infinite loop.

I have tried debugging it by outputting various values but still no success.

My Bfs Code


    int s=0;
    bool vis[n];
    int dist[n];

    for(int i=0;i<n;i++){
        vis[i]=false;
        dist[i]=INT_MAX;
    }

    dist[s]=0;
    vis[s]=true;
    q_push(s);



    while(!q_isEmpty()){
        int u = queu[0];
        for(int v=0;v<n;v++){
            if(adjMat[u][v]==1){
                if(vis[v]==false){
                    vis[v] == true;
                    dist[v]=dist[u]+1;
                    q_push(v);
                    cout<<v;
                }
            }
        }

        q_pop();


    }

My queue is globally declared its code

vector <int> queu;

void q_push(int d){
    queu.insert(queu.end(),d);

}

void q_pop(){
    queu.erase(queu.begin());
}

bool q_isEmpty(){
    return queu.empty();
}

I take adjacency matrix as input its code.

int n;
cin>>n;
for(int i=0;i<n;i++){
    for(int j=0;j<n;j++){
        int temp;
        cin>>temp;
        adjMat[i][j]=temp;
    }
}

Solution

  • Change this:

    vis[v] == true;
    

    to this:

    vis[v] = true;
    

    since you want to mark the adjacent node v as visited, by assigning it the value true - you mistakenly used the comparison operator instead of the assignment operator, so you keep and keep visiting nodes that you already traversed, again and again, going into an infinite loop..

    PS: Not the cause of the infinite loop, but as @PaulMcKenzie commented, you could/should use an std::queue.