1 struct edge{ 2 int to,cost; 3 edge(){ this->to = 0; this->cost = 0;} 4 edge(int t){ this->to = t; this->cost = 0;} 5 }; 6 class Solution { 7 public: 8 void addEdge(vector<edge> &edgelist, vector<vector<int>> &G, int from, int to){ 9 edge e = edge(to); 10 edgelist.push_back(e); 11 G[from].push_back(edgelist.size()-1); 12 } 13 bool isCyclic(vector<edge> &edgelist, vector<vector<int>> &G, vector<bool> vis, vector<bool> recStack, int v){ 14 for(int i=0;i<G[v].size();++i){ 15 edge e = edgelist[G[v][i]]; 16 if(recStack[e.to]) return false; // has cycle 17 if(!vis[e.to]){ 18 vis[e.to] = true; recStack[e.to] = true; 19 if(!isCyclic(edgelist, G, vis, recStack, e.to)) return false; // has cycle 20 recStack[e.to] = false; 21 } 22 } 23 return true; 24 } 25 bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { 26 vector<edge> edgelist; edgelist.clear(); 27 vector<vector<int> > G(numCourses); 28 for(int i=0;i<G.size();++i) G[i].clear(); 29 30 for(int i=0;i<prerequisites.size();++i){ 31 pair<int, int> pr = prerequisites[i]; 32 addEdge(edgelist, G, pr.first, pr.second); 33 } 34 35 vector<bool> vis(numCourses); 36 vector<bool> recStack(numCourses); 37 for(int i=0;i<numCourses;++i){ 38 if(!vis[i]){ 39 vis[i] = true; recStack[i] = true; 40 if(!isCyclic(edgelist, G, vis, recStack, i)) return false; // has cycle 41 recStack[i] = false; 42 } 43 } 44 45 return true; 46 } 47 };