刚刚学了下拓扑排序,于是找了道题来做下
代码如下
class Solution {
public:
struct node{
int val;
node* next;
node(){
val=-1;
next=0;
}
};
vector<node*> nodes;
vector<int> in;
vector<int> left;
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
node n;
vector<int> result;
for(int i=0;i<numCourses;i++){
nodes.push_back(0);
in.push_back(0);
left.push_back(i);
}
for(int i=0;i<prerequisites.size();i++){
int v1=prerequisites[i].first;
int v2=prerequisites[i].second;
node* new_node=new node;
new_node->val=v1;
new_node->next=nodes[v2];
nodes[v2]=new_node;
in[v1]++;
}
while(left.size()){
bool check=false;
for(vector<int>::iterator i=left.begin();i!=left.end();i++){
if(!in[*i]){
node* ptr=nodes[*i];
result.push_back(*i);
while(ptr!=NULL){
in[ptr->val]--;
ptr=ptr->next;
}
i=left.erase(i);
check=true;
break;
}
}
if(!check){
vector<int> tmp;
return tmp;
}
}
return result;
}
};