207. Course Schedule
There are a total of n courses you have to take, labeled from 0
to n-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?
Example 1:
Example 2:
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.
解题要点:
在脑子里(现实中也要)构造一个directed graph,后面的prerequisite课程指向前面的课程,所以我们可以有一个hashmap/dictionary来存上完这个课程后,可以上什么课。同时也需要记录一个indegree,当前课程有几个prerequisite。把indegree为0的课程先放到queue里,每处理一个,把它后续的课程indegree减1,如果为0,加进queue。最后检测在给出的课程数量里,它们的indegrees是否都为0。
Last updated
Was this helpful?