File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * <a href="https://leetcode.com/problems/course-schedule/">week10-3. course-schedule </a>
3
+ * <li>Description: Return true if you can finish all courses. Otherwise, return false </li>
4
+ * <li>Topics: Depth-First Search, Breadth-First Search, Graph, Topological Sort </li>
5
+ * <li>Time Complexity: O(N+E), Runtime 7ms </li>
6
+ * <li>Space Complexity: O(N+E), Memory 45.68MB </li>
7
+ * <li>Note : refer to the answer. remember the topic of topological sort </li>
8
+ */
9
+ class Solution {
10
+ public boolean canFinish (int numCourses , int [][] prerequisites ) {
11
+ int [] inDegree = new int [numCourses ];
12
+ List <List <Integer >> graph = new ArrayList <>();
13
+ for (int i =0 ; i <numCourses ; i ++){
14
+ graph .add (new ArrayList <>());
15
+ }
16
+
17
+ for (int [] pre : prerequisites ) {
18
+ int dest = pre [0 ], src = pre [1 ];
19
+ graph .get (src ).add (dest );
20
+ inDegree [dest ]++;
21
+ }
22
+
23
+ Queue <Integer > queue = new LinkedList <>();
24
+ for (int i =0 ; i <numCourses ; i ++) {
25
+ if (inDegree [i ] == 0 ) {
26
+ queue .offer (i );
27
+ }
28
+ }
29
+
30
+ int count = 0 ;
31
+ while (!queue .isEmpty ()){
32
+ int node = queue .poll ();
33
+ count ++;
34
+
35
+ for (int neighbor : graph .get (node )) {
36
+ inDegree [neighbor ]--;
37
+ if (inDegree [neighbor ] == 0 ) {
38
+ queue .offer (neighbor );
39
+ }
40
+ }
41
+ }
42
+
43
+ return count == numCourses ;
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments