Skip to content

Commit 278342c

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 207_Course_Schedule.java
1 parent bbf2274 commit 278342c

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

Topological Sort/.gitkeep

Whitespace-only changes.
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public boolean canFinish(int numCourses, int[][] prerequisites) {
3+
List<Integer>[] adjList = new ArrayList[numCourses];
4+
int[] indegrees = new int[numCourses];
5+
Queue<Integer> q = new LinkedList<>();
6+
int courseCount = 0;
7+
8+
for (int i = 0; i < numCourses; i++) {
9+
adjList[i] = new ArrayList<>();
10+
}
11+
for (int[] pair : prerequisites) {
12+
adjList[pair[1]].add(pair[0]);
13+
++indegrees[pair[0]];
14+
}
15+
16+
for (int i = 0; i < indegrees.length; i++) {
17+
if (indegrees[i] == 0) {
18+
q.offer(i);
19+
}
20+
}
21+
22+
while (!q.isEmpty()) {
23+
int course = q.poll();
24+
++courseCount;
25+
26+
for (int prereqCourse : adjList[course]) {
27+
if (--indegrees[prereqCourse] == 0) {
28+
q.offer(prereqCourse);
29+
}
30+
}
31+
}
32+
33+
return courseCount == numCourses;
34+
}
35+
}

0 commit comments

Comments
 (0)