import java.util.*;
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
Map<Integer,Integer> map = new HashMap<>();
for(int num=0;num< numCourses;num++) map.put(num,0);
Map<Integer,List<Integer>> con = new HashMap<>();
//初始化记录数,地图由拥有入读的Map类型来记录
for(int[] arr : prerequisites){
List<Integer> nextList = con.get(arr[1]);
if(nextList == null) {
nextList = new LinkedList<>();
con.put(arr[1],nextList);
}
int inp = map.get(arr[0]);
map.put(arr[0],inp + 1);
nextList.add(arr[0]);
}
LinkedList<Integer> queue = new LinkedList<>();
//初始化先决条件
for(int num=0;num< numCourses;num++){
if(map.get(num) == 0) queue.add(num);
}
//通过先决条件来开路
while(queue.size() != 0){
int pre = queue.removeLast();
List<Integer> nextList = con.get(pre);
if(nextList == null) continue;
for(int next : nextList){
int inp = map.get(next) - 1;
map.put(next,inp);
if(inp == 0) queue.add(next);
}
}
for(int num=0;num< numCourses;num++){
if(map.get(num) != 0) return false;
}
return true;
}
}
没想象的难。就这样吧