Problem overview
The method CanFinish receives numCourses, the number of courses (labelled 0 to numCourses - 1), and prerequisites, an int[][] of pairs [a, b]. A pair means course b must be taken before course a. It returns true if all the courses can be finished and false otherwise.
With numCourses = 2 and [[1,0]], take 0, then 1: true. With [[1,0],[0,1]], each course waits for the other, so neither can start: false. With 4 courses and [[1,0],[2,0],[3,1],[3,2]], course 0 needs nothing, courses 1 and 2 need 0, and course 3 needs both 1 and 2, so the order 0, 1, 2, 3 works.
Approach: take courses that have no prerequisites left
Draw each pair as an arrow from the course to take first to the course that needs it. The courses can all be finished exactly when there is an order of them in which every arrow points forward (a topological order), and that is possible exactly when the arrows contain no cycle.
This lesson builds such an order with Kahn's algorithm:
- Count, for every course, how many of its prerequisites are not taken yet. This is its in-degree, the number of arrows pointing into it.
- Put the courses with count 0 in a queue: they can be taken now.
- Take a course from the queue. For each course that was waiting for it, lower its count by one. If a count reaches 0, that course is free: add it to the queue.
- Repeat until the queue is empty. If all the courses were taken, the answer is
true.
Courses on a cycle wait for each other, so their counts never reach 0 and they are never taken. Neither is any course that needs one of them. So the number of courses taken falls short of numCourses exactly when a cycle exists.
Step by step
- Create
graph, aList<List<int>>.graph[b]will hold the courses that wait for courseb. - Add one empty list per course in a loop from 0 to
numCourses - 1. There is no one-line way to build a list of separate lists, so eachnew List<int>()is added on its own. - Create
inDegree, anint[]of lengthnumCourses. It starts with zeros, which is the right start. - Read the pairs with
foreach (int[] prereq in prerequisites). For each, addprereq[0]tograph[prereq[1]]and increaseinDegree[prereq[0]]. After the loop,inDegree[a]is the number of pairs whose first number isa. - Fill the queue. Create a
Queue<int>andEnqueueevery course whose in-degree is 0. These are where any valid order can start. - Count the courses taken with an
int takenthat starts at 0. - Loop while
queue.Count > 0.Dequeuea course, add 1 totaken, and go throughgraph[course]. For eachnextCourse, subtract 1 from its in-degree, and if it reaches 0,Enqueueit. A count reaches 0 only once, so each course enters the queue at most once. - Return
taken == numCourses.
For the 4-course example the setup gives this:
inDegree=[0,1,1,2]
0 -> [1,2]
1 -> [3]
2 -> [3]
3 -> []
Only course 0 starts in the queue. Taking it frees courses 1 and 2. Taking those, in turn, lowers the in-degree of 3 to 1 and then to 0. The courses come out in the order 0, 1, 2, 3, so taken is 4 and the method returns true.
The solution in C#
class Solution {
public bool CanFinish(int numCourses, int[][] prerequisites) {
List<List<int>> graph = new List<List<int>>();
for (int i = 0; i < numCourses; i++) {
graph.Add(new List<int>());
}
int[] inDegree = new int[numCourses];
foreach (int[] prereq in prerequisites) {
graph[prereq[1]].Add(prereq[0]);
inDegree[prereq[0]]++;
}
Queue<int> queue = new Queue<int>();
for (int course = 0; course < numCourses; course++) {
if (inDegree[course] == 0) {
queue.Enqueue(course);
}
}
int taken = 0;
while (queue.Count > 0) {
int course = queue.Dequeue();
taken++;
foreach (int nextCourse in graph[course]) {
inDegree[nextCourse]--;
if (inDegree[nextCourse] == 0) {
queue.Enqueue(nextCourse);
}
}
}
return taken == numCourses;
}
}
The C# details worth knowing:
List<T>andQueue<T>live inSystem.Collections.Generic. In a file of your own, addusing System.Collections.Generic;at the top.- Queue members.
Enqueueadds at the back,Dequeueremoves from the front, andCountis a property, written without parentheses. AList<T>also usesCount, while arrays useLength. - Two variables named
course. The first lives only inside theforloop, and the second inside thewhileloop. C# allows this because their scopes don't overlap. - Array elements start at zero.
new int[numCourses]is filled with 0, which is whyinDegreeneeds no initialising loop.
Complexity
Let V be numCourses and E the number of pairs.
Time: O(V + E). Building the graph takes one pass over the pairs plus V list creations. Each course enters the queue at most once, and when it leaves, its list is scanned once, so every pair is looked at one time in total.
Space: O(V + E) for the adjacency lists, the in-degree array and the queue.
Edge cases and common mistakes
- No prerequisites. Every in-degree is 0, all the courses enter the queue, and the answer is
true. FornumCourses = 5and an empty array it returnstrue. - Every course waits for another. The queue starts empty,
takenstays 0 and the answer isfalse. - A cycle in part of the graph. With 3 courses and
[[1,0],[2,1],[1,2]], course 0 is taken, but courses 1 and 2 wait for each other, so only 1 of 3 courses is taken and the result isfalse. - Mixing up the pair.
prereq[1]is the course to take first andprereq[0]the one that waits. Keep the same direction in the graph and in the in-degrees, or the counts won't match the lists they are lowered through. - Enqueuing more than once. Enqueue a course only when its count reaches exactly 0, not whenever it is lower.
- Using recursion. A recursive search over a long chain of 100,000 courses risks a stack overflow. The queue-based version has no such limit.
Testing
2, [[1,0]]givestrue.2, [[1,0],[0,1]]givesfalse.4, [[1,0],[2,0],[3,1],[3,2]]givestrue.3, [[1,0],[2,1],[1,2]]givesfalse.1with no pairs givestrue.
