File tree 1 file changed +39
-0
lines changed
1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ # Time Complexity: O(n)
3
+ # Space Complexity: O(n)
4
+ 위상 정렬을 사용해서 풀었습니다.
5
+ */
6
+
7
+ class Solution {
8
+ public boolean canFinish (int numCourses , int [][] prerequisites ) {
9
+ int [] inDegree = new int [numCourses ];
10
+ Queue <Integer > queue = new LinkedList <>();
11
+ List <List <Integer >> graph = new ArrayList <>();
12
+ for (int i = 0 ; i < numCourses ; i ++) {
13
+ graph .add (new ArrayList <>());
14
+ }
15
+
16
+ for (int i = 0 ; i < prerequisites .length ; i ++) {
17
+ graph .get (prerequisites [i ][1 ]).add (prerequisites [i ][0 ]);
18
+ inDegree [prerequisites [i ][0 ]]++;
19
+ }
20
+
21
+ for (int i = 0 ; i < numCourses ; i ++) {
22
+ if (inDegree [i ] == 0 ) queue .offer (i );
23
+ }
24
+
25
+ while (!queue .isEmpty ()) {
26
+ int curr = queue .poll ();
27
+
28
+ for (int next : graph .get (curr )) {
29
+ inDegree [next ]--;
30
+ if (inDegree [next ] == 0 ) queue .offer (next );
31
+ }
32
+ }
33
+
34
+ for (int i = 0 ; i < numCourses ; i ++) {
35
+ if (inDegree [i ] > 0 ) return false ;
36
+ }
37
+ return true ;
38
+ }
39
+ }
You can’t perform that action at this time.
0 commit comments