Skip to content

Commit 9083b8b

Browse files
committed
solve course schedule
1 parent 6b9bb1e commit 9083b8b

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

course-schedule/sora0319.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
public class Solution {
2+
public boolean canFinish(int numCourses, int[][] prerequisites) {
3+
int[] degree = new int[numCourses];
4+
5+
Map<Integer, List<Integer>> graph = new HashMap<>();
6+
7+
for (int[] p : prerequisites) {
8+
int course = p[0];
9+
int pre = p[1];
10+
11+
degree[course]++;
12+
13+
if (!graph.containsKey(pre)) {
14+
graph.put(pre, new ArrayList<>());
15+
}
16+
graph.get(pre).add(course);
17+
}
18+
19+
Queue<Integer> q = new LinkedList<>();
20+
for (int i = 0; i < numCourses; i++) {
21+
if (degree[i] == 0) {
22+
q.offer(i);
23+
}
24+
}
25+
26+
int finishedCourses = 0;
27+
28+
while (!q.isEmpty()) {
29+
int curr = q.poll();
30+
finishedCourses++;
31+
32+
if (graph.containsKey(curr)) {
33+
for (int neighbor : graph.get(curr)) {
34+
degree[neighbor]--;
35+
if (degree[neighbor] == 0) {
36+
q.offer(neighbor);
37+
}
38+
}
39+
}
40+
}
41+
42+
if(finishedCourses == numCourses) return true;
43+
44+
return false;
45+
}
46+
}

0 commit comments

Comments
 (0)