dataStructure@ Check if a directed graph has cycles
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<limits> 5 #include<vector> 6 using namespace std; 7 const int maxn = 10; 8 struct edge{ 9 int to, cost; 10 edge(int t){ 11 this->to = t; this->cost = 0; 12 } 13 }; 14 void addEdge(vector<edge> &edgelist, vector<vector<int> > &G, int from, int to){ 15 edgelist.push_back(edge(to)); 16 G[from].push_back(edgelist.size()-1); 17 } 18 void addDoubleEdge(vector<edge> &edgelist, vector<vector<int> > &G, int from, int to){ 19 addEdge(edgelist,G,from,to); 20 addEdge(edgelist,G,to,from); 21 } 22 bool isCyclic(vector<edge> edgelist, vector<vector<int> > G,vector<bool> vis, vector<bool> RecStack, int v){ 23 for(int i=0;i<G[v].size();++i){ 24 edge e = edgelist[G[v][i]]; 25 if(RecStack[e.to]) return true; 26 if(!vis[e.to]){ 27 vis[e.to] = true; RecStack[e.to] = true; 28 if(isCyclic(edgelist,G,vis,RecStack,e.to)) return true; 29 RecStack[e.to] = false; 30 } 31 } 32 return false; 33 } 34 void buildMap(vector<edge> &edgelist, vector<vector<int> > &G){ 35 addEdge(edgelist,G,0,1); 36 addEdge(edgelist,G,0,2); 37 addEdge(edgelist,G,2,0); 38 addEdge(edgelist,G,1,2); 39 addEdge(edgelist,G,2,3); 40 addEdge(edgelist,G,3,3); 41 } 42 int main(){ 43 vector<edge> edgelist; 44 vector<vector<int> > G(maxn); 45 vector<bool> vis(maxn); 46 vector<bool> RecStack(maxn); 47 48 buildMap(edgelist,G); 49 50 for(int i=0;i<vis.size();++i) vis[i]=false; 51 for(int i=0;i<RecStack.size();++i) RecStack[i]=false; 52 53 for(int i=0;i<G.size();++i){ 54 if(!vis[i]){ 55 vis[i] = true; RecStack[i] = true; 56 if(isCyclic(edgelist,G,vis,RecStack,i)){ 57 cout<<i<<" starts a cycle"<<endl; 58 } 59 RecStack[i] = false; 60 } 61 } 62 63 return 0; 64 }