Leetcode 210. Course Schedule II (topological sequencing-finding the presence of loops in a graph)

Source: Internet
Author: User

and Leetcode 207. Course Schedule (Topological ordering-finding the presence of loops in a graph) is similar.


Notice that the parallel or self-loops that may appear in the input are p:prerequistites in the for (auto).


Code:

Class solution {public:vector<int> FindOrder (int numcourses, vector<pair<int, int>>& Prerequisi TES) {//[0, {1, 2, 3}], means after finishing #0, "might" being able to take #1, #2, #3//That's, you must    Finish #0, before trying to take #1, #2, #3 map<int, vector<int>> course_chain;    Vector<int> In_degree (numcourses, 0);    Queue<int> Q;    vector<int> ret;        for (auto p:prerequisites) {//Self-loop, return empty vector.    if (P.first = = P.second) {return vector<int> (); }//No duplicate edges input if (find (Course_chain[p.second].begin (), Course_chain[p.second].end (), p.first) = = Cou    Rse_chain[p.second].end ()) {course_chain[p.second].push_back (P.first);    + + In_degree[p.first];    }} for (size_t i = 0; i < numcourses; + + i) {if (in_degree[i] = = 0) {Q.push (i);    }} for (;!q.empty (); Q.pop ()) {int pre_course = Q.front (); Ret.puSh_back (Pre_course);    for (Auto it = Course_chain[pre_course].begin (); It! = Course_chain[pre_course].end (); + + it) {--in_degree[*it];    if (in_degree[*it] = = 0) {Q.push (*it); }}} return Ret.size () ==numcourses?    Ret:vector<int> (); }};


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode 210. Course Schedule II (topological sequencing-finding the presence of loops in a graph)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.