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?
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
if(prerequisites.length == 0)
return true;
int[] indegree = new int[numCourses];
Arrays.fill(indegree, -1);
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
int count = 0;
for(int[] p: prerequisites){
if(!map.containsKey(p[0])){
indegree[p[0]] = 0;
map.put(p[0], new ArrayList<Integer>());
count++;
}
if(!map.containsKey(p[1])){
indegree[p[1]] = 1;
map.put(p[1], new ArrayList<Integer>());
count++;
}
else{
indegree[p[1]]++;
}
map.get(p[0]).add(p[1]);
}
Queue<Integer> q = new LinkedList<Integer>();
for(int i = 0; i < indegree.length; i++){
if(indegree[i] == 0){
q.offer(i);
}
}
while(!q.isEmpty()){
int temp = q.poll();
count--;
if(map.get(temp) != null){
for(int a: map.get(temp)){
if(--indegree[a] == 0){
q.offer(a);
}
}
}
}
return count == 0;
}
}