Cycle Detection in unirected Graph (bfs)

PHOTO EMBED

Tue Aug 06 2024 06:35:19 GMT+0000 (Coordinated Universal Time)

Saved by @w3yogesh #c++

// Driver function
        for(int i = 0; i < V; i++){
            if(!vis[i]) {
                if(cycleBFS(i, vis, adj)) return true;
            }
        }



// cycle check fun by BFS
    bool cycleBFS(int src, vector<int> &vis, vector<int> adj[]){
        queue<pair<int,int>> q;
        vis[src] = 1;
        q.push({src,-1});
        
        while(!q.empty()){
            int node = q.front().first;
            int parent = q.front().second;
            q.pop();
            
            for(auto it: adj[node]){
                if(!vis[it]){
                    vis[it] = 1;
                    q.push({it, node});
                }
                else if(parent != it){
                    return true;
                }
            }
        }
        return false;
    }




content_copyCOPY

https://www.geeksforgeeks.org/problems/detect-cycle-in-an-undirected-graph/1