8
8
import java .util .Queue ;
9
9
import java .util .Set ;
10
10
11
+ /**
12
+ * 207. Course Schedule
13
+ * <p>
14
+ * There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1.
15
+ * You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
16
+ * For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
17
+ * Return true if you can finish all courses. Otherwise, return false.
18
+ * <p>
19
+ * Example 1:
20
+ * Input: numCourses = 2, prerequisites = [[1,0]]
21
+ * Output: true
22
+ * Explanation: There are a total of 2 courses to take.
23
+ * To take course 1 you should have finished course 0. So it is possible.
24
+ * <p>
25
+ * Example 2:
26
+ * Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
27
+ * Output: false
28
+ * Explanation: There are a total of 2 courses to take.
29
+ * To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
30
+ * <p>
31
+ * Constraints:
32
+ * 1 <= numCourses <= 2000
33
+ * 0 <= prerequisites.length <= 5000
34
+ * prerequisites[i].length == 2
35
+ * 0 <= ai, bi < numCourses
36
+ * All the pairs prerequisites[i] are unique.
37
+ */
11
38
public class _207 {
12
39
13
40
public static class Solution1 {
@@ -33,11 +60,11 @@ public boolean canFinish(int numCourses, int[][] prerequisites) {
33
60
Iterator <Integer > it = zeroDegree .iterator ();
34
61
int course = it .next ();
35
62
zeroDegree .remove (course );
36
- for (int [] prereq : prerequisites ) {
37
- if (prereq [1 ] == course ) {
38
- indegree [prereq [0 ]]--;
39
- if (indegree [prereq [0 ]] == 0 ) {
40
- zeroDegree .add (prereq [0 ]);
63
+ for (int [] pre : prerequisites ) {
64
+ if (pre [1 ] == course ) {
65
+ indegree [pre [0 ]]--;
66
+ if (indegree [pre [0 ]] == 0 ) {
67
+ zeroDegree .add (pre [0 ]);
41
68
}
42
69
}
43
70
}
@@ -93,7 +120,7 @@ public boolean canFinish(int numCourses, int[][] prerequisites) {
93
120
public static class Solution3 {
94
121
/**
95
122
* DFS, the fastest method in all, with the help of a cache and also converted edges into adjacency list,
96
- * although theoretically, all these three methods' time complexity is : O(V+E)
123
+ * although theoretically, all these three methods' time complexity are : O(V+E)
97
124
*/
98
125
public boolean canFinish (int numCourses , int [][] prerequisites ) {
99
126
List <List <Integer >> courseList = new ArrayList <>();
0 commit comments