Topological sorting. This is my DFS solution. Please note that I used _rec to avoid duplicate checking.
class Solution { public: map<int, int> rec; set<int> _rec; bool go(map<int, vector<int>> &m, int inx, int level) { rec[inx] = level; _rec.insert(inx); for (auto i : m[inx]) { if (rec[i] != -1 && rec[i] < level) return false; bool b = go(m, i, level + 1); if (!b) return false; } rec[inx] = -1; return true; } bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { map<int, vector<int>> m; for (auto &r : prerequisites) { m[r.second].push_back(r.first); } for (int i = 0; i < numCourses; i++) rec[i] = -1; for (auto &r : m) { if(_rec.find(r.first) != _rec.end()) continue; bool ret = go(m, r.first, 0); if (!ret) return false; } return true; } };