Leetcode-Course Schedule
Question: leetcode
Course Schedule
There are a total of n courses you have to take, labeled from0
Ton - 1
.
Some courses may have 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, is it possible for you to finish all courses?
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you shoshould have finished course 0. So it is possible.
2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you shoshould have finished course 0, and to take course 0 you shoshould also have finished course 1. So it is impossible.
Analysis:
This topic can be converted to "determining whether a ring exists in a directed graph ".
1. Put the content in the array prerequisites into the hash table. The key of the table is the course number, and the value is an array. It records the constraints of the course represented by the key (that is, the course in the value is completed, to go to the key course ). If each course is regarded as a point on the plane, each course in the key and value can be connected into a directed path.
2. Use the backtracking method. If no ring exists, delete the corresponding "path" until the directed graph is deleted. If a ring exists, the entire program returns false.
Class Solution {public: bool canFinish (int numCourses, vector
> & Prerequisites) {if (prerequisites. size () <= 1) return true; unordered_map
> Table; for (auto & I: prerequisites) {table [I [0]. push_back (I [1]);} vector
Path; while (! Table. empty () {auto it = table. begin (); path. push_back (it-> first); if (HasLoop (table, it-> first, path) return false; path. pop_back ();} return true;} // determines whether a ring exists. If a ring exists, true is returned. Otherwise, false bool HasLoop (unordered_map) is returned.
> & Table, const int & begin, vector
& Path) {if (table. count (begin) = 0) return false; while (! Table [begin]. empty () {int temp = table [begin]. back (); if (find (path. begin (), path. end (), temp )! = Path. end () return true; path. push_back (temp); if (HasLoop (table, temp, path) return true; path. pop_back (); table [begin]. pop_back ();} table. erase (begin); return false ;}};