207. Course Schedule

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

For example:

1
2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

1
2, [[1,0],[0,1]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

解法1:有向图

这题和Course Schedule II的解法基本一样,就是判断有向图中是否有环。基本的入度出度的解法要掌握。
C++

1

Java

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
39
40
41
42
43
44
45
46
47
48
49
50
51
public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
if (prerequisites == null || prerequisites.length == 0) {
return true;
}
// no circle in the graph + number of visited nodes == numCourses
int[] ins = new int[numCourses];
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
for (int[] pre : prerequisites) {
if (!map.containsKey(pre[1])) {
map.put(pre[1], new ArrayList<Integer>());
}
map.get(pre[1]).add(pre[0]); // because of no duplicate edges in the input prerequisities
ins[pre[0]]++; // add the in-count for the node
}
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < numCourses; i++) {
if (ins[i] == 0) {
queue.offer(i);
}
}
while (!queue.isEmpty()) {
int root = queue.poll();
if (map.containsKey(root)) {
List<Integer> children = map.get(root);
for (int child : children) {
ins[child] -= 1;
if (ins[child] == 0) {
queue.offer(child);
}
}
}
}
// check if there is non-zero ins
for (int i = 0; i < numCourses; i++) {
if (ins[i] != 0) {
return false;
}
}
return true;
}
}