lc207-Course Schedule 發表於 2016-12-13 | 分類於 leetcode | 0 comments | 1234567891011121314151617181920212223242526272829303132333435363738394041class graph { vector<unordered_set<int>> adj; int n; vector<int> temp_visited; vector<int> perm_visited;public: void add_edge(int u, int v) { adj[u].insert(v); } graph(int V, vector<pair<int, int>>& prerequisites):perm_visited(V, 0), temp_visited(V, 0), adj(V, unordered_set<int>()) { n = V; for (auto p:prerequisites) { add_edge(p.second, p.first); } } bool containsCycle() { for (int i = 0; i < n; i++) if (!perm_visited[i]) if (dfs(i)) return true; return false; } bool dfs(int cur) { if (perm_visited[cur]) return false; temp_visited[cur] = 1; for (int next:adj[cur]) { if (temp_visited[next]) return true; if (dfs(next)) return true; } temp_visited[cur] = 0; perm_visited[cur] = 1; return false; }};class Solution {public: bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { graph g(numCourses, prerequisites); return !(g.containsCycle()); }};