Topic
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.
Note:
- The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more on how a graph is represented.
- Assume that there is no duplicate edges in the input prerequisites.
Thinking of solving problems
- The essence is a topological sort problem.
- Calculate and store the degrees and degrees of each task
- Place a zero-in task in a queue
- The 0-in queue is continuously ejected, and the out-of-order relationship is maintained (removed), and when the task's zero-in degree is maintained, the queue is queued until it is empty.
Class solution (Object): Def canfinish (self, numcourses, prerequisites): "" ": Type Numcourses:int : Type Prerequisites:list[list[int]]: Rtype:bool "" "# Create in-degree out-of-degrees empty dictionary indegree, Outdegree = {x:[] For x in range (numcourses)}, {x:[] for x in range (numcourses)} # stores the in-degree-out relationship for course, precourse in P Rerequisites:indegree[course].append (Precourse) outdegree[precourse].append (course) count, Emptyqueue = 0, [] # The task of entering zero into the queue for I in range (numcourses): If not indegree. Get (i): Emptyqueue.append (i) # Popup task, maintenance task While Emptyqueue:node = Emptyqueue.pop () Count + = 1 for j in Outdegree[node]: Indegree[j].remove (node) If not Indegree.get (j): Emptyqueue.append (j) return count = = Numcou RSes
Leetcode 207. Course Schedule (topological sort)