Whether is possible to finish all the course depends on whether there is a circle prerequisites in the course list. Hence, we only need to compute if there is a topological ordering of the courses.
Steps of the algorithm (BFS):
Find vertices with in-degree of 0, put them into a queue
While queue is not empty, poll the queue, find the vertices which are pointed by the vertices we just polled from the queue
If there is no vertex left in the graph, then there is a valid topological ordering
From Wikipedia: a BFS method
1
2
3
4
5
6
7
8
9
10
11
12
13
L ← Empty list that will contain the sorted elements
int[] indegrees = newint[numCourses]; // how many pre for course[i]
for (int[] pair : prerequisites) {
indegrees[pair[0]]++;
}
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < indegrees.length; i++) {
if (indegrees[i] == 0) {
q.offer(i);
}
}
int count = q.size();
while (!q.isEmpty()) {
int i = q.poll();
for (int[] pair : prerequisites) {
if (pair[1] == i) {
indegrees[pair[0]]--;
if (indegrees[pair[0]] == 0) {
q.offer(pair[0]);
count++;
}
}
}
}
return count == numCourses;
}
}
The running time is O(v^2) since the while loop is O(V) and there is a for loop for O(V) inside. We can improve the speed by building a adjacent list for the neighbor of vertex.