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)