course schedule 2
1)利用indegree记录每一个课程要多少个条件;
2)每次选取所需条件为0的课学习,并对indegree表进行update;
3)知道indegree表变为0;
class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<int> seq;
if(numCourses == 0)
{
return seq;
}
map<int, int> ind;
for(int i = 0; i<numCourses; i++)
{
ind[i] = 0;
}
for(pair<int, int> tmp : prerequisites)
{
ind[tmp.first]++;
}
bool circle = false;
while(ind.size() != 0 && !circle)
{
circle = true;
int courseno = -1;
for(auto& kv : ind)
{
if(kv.second != 0)
{
continue;
}
circle = false;
courseno = kv.first;
break;
}
if(circle)
{
vector<int> circleSeq;
return circleSeq;
}
ind.erase(courseno);
seq.push_back(courseno);
for(pair<int, int> tmp : prerequisites)
{
if(tmp.second == courseno)
{
ind[tmp.first]--;
}
}
}
return seq;
}
};