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:
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.
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.
- This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
- There are several ways to represent a graph. For example, the input prerequisites is a graph represented by a list of edges. Is this graph representation appropriate?
- Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
- Topological sort could also be done via BFS.
建立一个indegree的表,然后扫这个表,如果indegree为0,那么把这个node加入result,并更新他的所有子节点入度。
public boolean canFinish(int numCourses, int[][] prerequisites) {
int[] indegree = new int[numCourses];
int n = prerequisites.length;
if (n == 0) {
return true;
}
for (int i = 0; i < n; i++) {
indegree[prerequisites[i][0]]++;
}
int count = numCourses;
while (count > 0) {
boolean flag = false;
for(int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
indegree[i] = -1;
count--;
for (int j = 0; j < n; j++) {
if (prerequisites[j][1] == i) {
indegree[prerequisites[j][0]]--;
}
}
flag = true;
}
}
if (!flag) {
break;
}
}
return count == 0;
}
上面的做法比较费时间,O(V^2E), 找到入度为0的需要O(V),然后依次减少child node的degree。这个操作需要V次。
下面用空间换时间,先建立一个入度的map,找到indegree为0的节点后,因为我们已经知道了他的子节点list,直接更新所有node. 这样的时间为O(V+E)
public boolean canFinish(int numCourses, int[][] prerequisites) {
int[] indegree = new int[numCourses];
int n = prerequisites.length;
if (n == 0) {
return true;
}
Map<Integer, List<Integer>> nodes = new HashMap<Integer, List<Integer>>();
for (int i = 0; i < n; i++) {
int indegreeNode = prerequisites[i][0];
int outdegreeNode = prerequisites[i][1];
indegree[indegreeNode]++;
if (nodes.get(outdegreeNode) == null) {
nodes.put(outdegreeNode, new ArrayList<Integer>());
}
nodes.get(outdegreeNode).add(indegreeNode);
}
int count = numCourses;
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
indegree[i]--;
queue.offer(i);
count--;
}
}
while (!queue.isEmpty()) {
int zeroDegree = queue.poll();
List<Integer> list = nodes.get(zeroDegree);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
int num = list.get(i);
indegree[num]--;
if (indegree[num] == 0) {
indegree[num]--;
queue.offer(num);
count--;
}
}
}
}
return count == 0;
}