类似4.7 需要变化一下形式 4.7中课程不是数字 先构造graph 然后在操作现在看起来有点麻烦 以后再实现
/*
想写一个通用一点的 因为course不一定是数字 所以建立两个map 一个用于储存课程 与他需要的前置课程数量,另一个储存课程 与他后置的课程list
这样 利用bfs 每次把当前课程后置list的课程找出来 将前置课程已经为0的课程放置到queue里面 最终可以找出上课的顺序;
*/
public class Solution {
/*
* @param numCourses: a total of n courses
* @param prerequisites: a list of prerequisite pairs
* @return: the course order
*/
public int[] findOrder(int numCourses, int[][] prerequisites) {
if(numCourses == 0) return new int[]{};
Map<Integer, ArrayList<Integer>> postMap = new HashMap<>();
Map<Integer, Integer> prepMap = new HashMap<>();
int[] result = new int[numCourses];
for(int i = 0; i < numCourses; i++) {
postMap.put(i, new ArrayList<Integer>());
prepMap.put(i, 0);
}
for(int i = 0; i < prerequisites.length; i++) {
prepMap.put(prerequisites[i][0],prepMap.get(prerequisites[i][0]) + 1);
}
for(int i = 0; i < prerequisites.length; i++) {
postMap.get(prerequisites[i][1]).add(prerequisites[i][0]);
}
Queue<Integer> q = new LinkedList<>();
for(int i = 0; i < numCourses; i++) {
if(prepMap.get(i) == 0) {
q.offer(i);
}
}
int count = 0;
while(!q.isEmpty()){
int temp = q.poll();
result[count++] = temp;
for(Integer i : postMap.get(temp)) {
prepMap.put(i, prepMap.get(i) - 1);
if(prepMap.get(i) == 0) {
q.offer(i);
}
}
}
if(count == numCourses) {
return result;
}
return new int[]{};
}
}