SHARE
TWEET

Cycle detection

keverman Feb 20th, 2019 (edited) 74 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. int n;
  2. std::vector<std::vector<int>> edges;
  3. std::vector<bool> visited, rec;
  4.  
  5. bool cycle_dfs(int u)
  6. {
  7.     if(!visited[u])
  8.     {
  9.         visited[u] = rec[u] = true;
  10.  
  11.         for(int v : edges[u])
  12.             if((!visited[v] && cycle_dfs(v)) || rec[i])
  13.                 return true;
  14.     }
  15.  
  16.     rec[i] = false;
  17.     return false;
  18. }
  19.  
  20. bool has_cycles()
  21. {
  22.     visited.resize(n, false);
  23.     rec.resize(n, false);
  24.  
  25.     for(int i = 0; i < n; i++)
  26.         if(cycle_dfs(i))
  27.             return true;
  28.  
  29.     return false;
  30. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top