1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution { public: bool canFinish(int numCourses, vector<vector<int>>& prerequisites) { vector<vector<int>> map(numCourses); vector<bool> done(numCourses, false); vector<bool> todo(numCourses, false); for(auto& course : prerequisites) { map[course[1]].push_back(course[0]); } for(int i = 0; i < numCourses; ++i) { if(!helper(map, i, todo, done)) return false; } return true; } private: bool helper(vector<vector<int>>& map, int index, vector<bool>& todo, vector<bool>& done) { if(todo[index]) return false; if(done[index]) return true; done[index] = true; todo[index] = true; for(auto& i : map[index]) { if(!helper(map, i, todo, done)) { return false; } } todo[index] = false; return true; } };
|