Advertisement
Josif_tepe

Untitled

Mar 20th, 2024
523
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | None | 0 0
  1. class Solution {
  2.   public:
  3.  
  4.     // Function to detect cycle in an undirected graph.
  5.     vector<bool> visited;
  6.    
  7.     bool dfs(int node, int parent,  vector<int> adj[]) {
  8.         visited[node] = true;
  9.         for(int neigh : adj[node]) {
  10.             if(!visited[neigh] ) {
  11.                 if(dfs(neigh, node, adj))
  12.                     return true;
  13.             }
  14.             else if(neigh != parent) {
  15.                 return true;
  16.             }
  17.         }
  18.         return false;
  19.     }
  20.     bool isCycle(int V, vector<int> adj[]) {
  21.         visited = vector<bool>(V + 1, false);
  22.         for(int i = 1; i <= V; i++) {
  23.             if(!visited[i]) {
  24.                 if(dfs(i, 0, adj)) {
  25.                     return true;
  26.                 }
  27.             }
  28.         }
  29.         return false;
  30.     }
  31. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement