LeetCode "Course Schedule"
2015-05-13 14:37
295 查看
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; } };
相关文章推荐
- LeetCode "Course Schedule II"
- [LeetCode#210]Course Schedule II
- LeetCode Course Schedule
- leetcode207 Course Schedule java
- LeetCode Course Schedule
- [LeetCode]Course Schedule II
- leetcode:Course Schedule II
- [LeetCode] Course Schedule III 课程清单之三
- leetcode210——Course Schedule II
- Leetcode Course Schedule II
- [Leetcode 270, Medium] Course Schedule II
- LeetCode Course Schedule
- 【Leetcode】Course Schedule II
- Leetcode: Course Schedule II
- leetcode---Course Schedule II
- [LeetCode][JavaScript]Course Schedule II
- LeetCode 之 Course Schedule I
- [LeetCode] Course Schedule II 课程清单之二
- 【LeetCode】Course Schedule II 解题报告
- Course Schedule II -- leetcode