There is a total of n courses you have to take, labeled from 0 to n - 1 .
Some courses May has prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a Pair[0,1]
Given the total number of courses and a list of prerequisite pairs, are it possible for your to finish all courses?
For example:
2, [[1,0]]
There is a total of 2 courses to take. To take course 1 should has finished course 0. So it is possible.
2, [[1,0],[0,1]]
There is a total of 2 courses to take. To take course 1 should has finished course 0, and to take course 0 you should also has finished course 1. So it is impossible.
Basic idea: Topology sequencing
There are dependencies between courses.
1. Find out what pre-conditions are available for learning.
2. After completing this course, update other courses that depend on the course.
3. Repeat steps 1 and 2.
In the algorithm, a degree array is maintained, or an array of pre-degree classes is called. Indicates the number of pre-courses that need to be studied in order to learn the course.
If the value is 0, the course can start learning.
Class Solution {public: bool Canfinish (int numcourses, vector<pair<int, int>>& prerequisites) { vector<int> degree (numcourses); Unordered_set<int> finished_courses; for (auto p:prerequisites) ++degree[p.first]; for (int i=0; i<numcourses; i++) { if (!degree[i]) Finished_courses.insert (i); } int count = 0; while (!finished_courses.empty ()) { int course = *finished_courses.begin (); Finished_courses.erase (Finished_courses.begin ()); for (auto p:prerequisites) { if (P.second = = Course &&!--degree[p.first]) Finished_courses.insert ( P.first); } ++count; } return count = = numcourses; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Course Schedule--Leetcode