-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path207. Course Schedule.java
More file actions
38 lines (37 loc) · 1.14 KB
/
207. Course Schedule.java
File metadata and controls
38 lines (37 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
for(int i = 0; i < numCourses; i++){
graph.add(new ArrayList<>());
}
for(int[] edge : prerequisites){
int course = edge[0];
int prerequisite = edge[1];
graph.get(prerequisite).add(course);
}
int[] indegree = new int[numCourses];
for(int u = 0; u < numCourses; u++){
for(int v : graph.get(u)){
indegree[v]++;
}
}
Queue<Integer> queue = new LinkedList<>();
for(int i = 0; i < numCourses; i++){
if(indegree[i] == 0){
queue.add(i);
}
}
int count = 0;
while(!queue.isEmpty()){
int course = queue.poll();
count++;
for(int neighbour : graph.get(course)){
indegree[neighbour]--;
if(indegree[neighbour] == 0){
queue.add(neighbour);
}
}
}
return count == numCourses;
}
}