Advertisement
Josif_tepe

Untitled

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