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<pair<int, int>>& p) { vector<int> visited(n, -1); // un-visited vector<set<int>> v(n, set<int>()); 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<set<int>>& v, vector<int>& 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; } };
Topological Sort is another way.