★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-olocecra-ku.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
There are N
courses, labelled from 1 to N
.git
We are given relations[i] = [X, Y]
, representing a prerequisite relationship between course X
and course Y
: course X
has to be studied before course Y
.github
In one semester you can study any number of courses as long as you have studied all the prerequisites for the course you are studying.微信
Return the minimum number of semesters needed to study all courses. If there is no way to study all the courses, return -1
. 學習
Example 1:ui
Input: N = 3, relations = [[1,3],[2,3]] Output: 2 Explanation: In the first semester, courses 1 and 2 are studied. In the second semester, course 3 is studied.
Example 2:spa
Input: N = 3, relations = [[1,2],[2,3],[3,1]] Output: -1 Explanation: No course can be studied because they depend on each other.
Note:code
1 <= N <= 5000
1 <= relations.length <= 5000
relations[i][0] != relations[i][1]
有n個課程,從1到n標記。咱們獲得關係[i]=[x,y],表示課程x和課程y之間的先決條件關係:課程x必須在課程y以前學習。在一個學期內,你能夠學習任意數量的課程,只要你已經學習了你所學課程的全部先決條件。返回學習全部課程所需的最少學期數。若是沒有辦法學習全部課程,返回-1。htm
例1:blog
輸入:n=3,relations=[[1,3],[2,3]]
輸出:2
說明:
第一學期,學習課程1和2。第二學期,學習第三門課程。
例2:
輸入:n=3,relations=[[1,2],[2,3],[3,1]]
輸出:-1
說明:
任何課程都不能學習,由於它們相互依賴。
提示:
1 <= N <= 5000
1 <= relations.length <= 5000
relations[i][0] != relations[i][1]