jayati

Detect cycle in an undirected graph

Nov 13th, 2023
947
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // } Driver Code Ends
  6. class Solution {
  7.    
  8.   private:
  9.     bool detectcycle(int src,vector<int> adj[],int vis[])
  10.     {
  11.         vis[src]=1;
  12.         queue<pair<int,int>> q;
  13.         q.push({src,-1});
  14.         while(!q.empty())
  15.         {
  16.             int node=q.front().first;
  17.             int parent=q.front().second;
  18.             q.pop();
  19.            
  20.             for(auto adjnode:adj[node])
  21.             {
  22.                 if(!vis[adjnode])
  23.                 {
  24.                     vis[adjnode]=1;
  25.                     q.push({adjnode,node});
  26.                 }
  27.                 else if(parent!=adjnode)
  28.                 {
  29.                     return true;
  30.                 }
  31.             }
  32.         }
  33.         return false;
  34.     }
  35.   public:
  36.     // Function to detect cycle in an undirected graph.
  37.     bool isCycle(int V, vector<int> adj[]) {
  38.         // Code here
  39.             int vis[V]={0};
  40.             for(int i=0;i<V;i++)
  41.             {
  42.                 if(!vis[i])
  43.                 {
  44.                     if(detectcycle(i,adj,vis)==true)
  45.                     {
  46.                         return true;
  47.                     }
  48.                 }
  49.             }
  50.             return false;
  51.     }
  52. };
  53.  
  54. //{ Driver Code Starts.
  55. int main() {
  56.     int tc;
  57.     cin >> tc;
  58.     while (tc--) {
  59.         int V, E;
  60.         cin >> V >> E;
  61.         vector<int> adj[V];
  62.         for (int i = 0; i < E; i++) {
  63.             int u, v;
  64.             cin >> u >> v;
  65.             adj[u].push_back(v);
  66.             adj[v].push_back(u);
  67.         }
  68.         Solution obj;
  69.         bool ans = obj.isCycle(V, adj);
  70.         if (ans)
  71.             cout << "1\n";
  72.         else
  73.             cout << "0\n";
  74.     }
  75.     return 0;
  76. }
  77. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment