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.
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
这题主要用到的是拓扑排序。每次计算入度为0的点,放在一个queue里边,然后在一个循环里,每次取出queue中的一个元素i,把它加入结果,更新前置课为i的点 j 的入度(入度-1)。如果点 j 此时的入度0,那么把它加入到队列当中。
为了提高效率,代码里边的result可以替换为一个int count,最后判断count的值是否为nu mCourse ,不是的话说明有环。
代码:
public boolean canFinish(int numCourses, int[][] prerequisites) {
if(numCourses == 0) return true;
int [] inDegree = new int[numCourses];
//init
for(int i=0;i<prerequisites.length;i++){
inDegree[prerequisites[i][0]]++;
}
Queue<Integer> queue = new LinkedList<>();
for(int i=0;i<inDegree.length;i++){
if(inDegree[i] == 0){
queue.offer(i);
}
}
//List<Integer> result = new ArrayList<>();
int count = 0;
while(queue.size() != 0){
int cur = queue.poll();
//result.add(cur);
count++;
//update
inDegree[cur] = -1;
for(int i=0;i<prerequisites.length;i++){
if(prerequisites[i][1] == cur){
inDegree[prerequisites[i][0]]--;
if(inDegree[prerequisites[i][0]]==0){
queue.offer(prerequisites[i][0]);
}
}
}
}
if(count == numCourses) return true;
return false;
}