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.
对于我自己来说,这道题是BFS中最好理解的题,可以把它看作是一个有向图,然后根据不同的方向指向来删除最外层的节点,
code:
public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
int length = prerequisites.length;
if(numCourses == 0)
return true;
int[] number = new int[numCourses];
List<List<Integer>> record = new ArrayList<List<Integer>>();
for(int i = 0; i < numCourses; i++){
List<Integer> tem = new ArrayList<Integer>();
record.add(tem);
}
// System.out.print(record.size());
for(int i = 0; i < length; i++){
number[prerequisites[i][0]] ++;
record.get(prerequisites[i][1]).add(prerequisites[i][0]);
}
//record how many courses that we can take now
int result = 0;
Queue<Integer> queue = new LinkedList<Integer>();
for(int i = 0; i < numCourses; i++){
if(number[i] == 0){
queue.offer(i);
}
}
while(!queue.isEmpty()){
result++;
int courseNum = queue.poll();
List<Integer> connected = record.get(courseNum);
Iterator iterator = connected.iterator();
while(iterator.hasNext()){
int tem = (Integer)iterator.next();
number[tem]--;
if(number[tem] == 0){
queue.offer(number[tem]);
}
}
}
return result >= numCourses;
}
}