您的位置:首页 > 其它

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: