Leetcode 207. Course Schedule (topological sort-to see if there is a ring in the graph)

Source: Internet
Author: User

Ask if there is a ring in the graph.


Method One: Topological sequencing

Maintain all nodes with 0 in a queue, and each time a node v pops up, view all nodes from V to u;

Reduce the read-in of U by one, and if you are at 0, you will join the queue.

When the queue is empty, check the penetration of all nodes, and if all nodes are 0, there is a topological sort-there is no ring in the graph.

Code:

Class Solution{public:bool Canfinish (int numcourses, vector<pair<int, int>>& prerequisites) {vector <vector<bool>> map (numcourses, vector<bool> (Numcourses, false));vector<int> In_degree ( numcourses, 0); For_each (Prerequisites.begin (), Prerequisites.end (), [&map, &in_degree] (pair<int,int> P) {if (Map[p.first][p.second] = = False) {Map[p.first][p.second] = true;++ In_degree[p.second];}}); queue<int> q;for (int id = 0; ID < numcourses; + + ID) {if (in_degree[id] = = 0) {Q.push (id);}} while (!q.empty ()) {int course = Q.front (), Q.pop (), for (int id = 0; ID < numcourses; + + ID) {if (map[course][id] = = True) {--in_degree[id];if (in_degree[id] = = 0) {Q.push (id);}}}} Return all_of (In_degree.begin (), In_degree.end (), [] (int in)-Bool{return in = = 0;});};


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

Leetcode 207. Course Schedule (Topological sort-asks if there are loops in the 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.