LeetCode 210. Course Schedule II (topological sorting-determining whether a ring exists in a directed graph)

Source: Internet
Author: User

LeetCode 210. Course Schedule II (topological sorting-determining whether a ring exists in a directed graph)

Similar to LeetCode 207. Course Schedule (topological sorting-finding whether a ring exists in a directed graph.

 

Note that in for (auto p: prerequistites), the possible parallel edge or self-ring in the input is determined.

 

Code:

 

class Solution {public:    vector
 
   findOrder(int numCourses, vector
  
   >& prerequisites)     {    // [0, {1, 2, 3}], means after finishing #0, you might be able to take #1, #2, #3    // That is, you must finish #0, before trying to take #1, #2, #3    map
   
    > course_chain;    vector
    
      in_degree(numCourses, 0);    queue
     
       q;    vector
      
        ret; for (auto p: prerequisites) { // self-loop, return empty vector. if (p.first == p.second) { return vector
       
        (); } // no duplicate edges input if (find(course_chain[p.second].begin(), course_chain[p.second].end(), p.first) == course_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
        
         (); }};
        
       
      
     
    
   
  
 


 

Related Article

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.