https://leetcode.com/problems/course-schedule/description/
DFS, detect cycle. For each node, we have 3 states during DFS: 1) un-visited, 2) visiting, 3) visited.
class Solution {public: bool canFinish(int n, vector>& p) { vector visited(n, -1); // un-visited vector > v(n, set ()); for (int i = 0; i < p.size(); i++) { v[p[i].second].insert(p[i].first); } for (int i = 0; i < n; i++) if (visited[i] == -1 && dfs(v, visited, i)) return false; return true; } bool dfs(vector >& v, vector & visited, int n) { visited[n] = 1; // visiting for (auto nb : v[n]) { if (visited[nb] == 1) return true; else if (visited[nb] == 2) continue; else { if (dfs(v, visited, nb)) return true; } } visited[n] = 2; // visited return false; }};
is another way.