code
思路:利用入度(indegree),每次都将入度为0的课程删去,所有以次课程为前置的课程入度减1
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<Integer>[] pre = new LinkedList[numCourses];
Queue<Integer> queue = new LinkedList<>();
int[] indegree = new int[numCourses];
for (int i = 0; i < numCourses; i++)
pre[i] = new LinkedList<>();
for (int i = 0; i < prerequisites.length; i++) {
pre[prerequisites[i][1]].add(prerequisites[i][0]);
indegree[prerequisites[i][0]]++;
}
for (int i = 0; i < indegree.length; i++)
if (indegree[i] == 0) queue.offer(i);
int count = 0;
while (!queue.isEmpty()) {
int course = queue.poll();
count++;
for (int adj : pre[course])
if (--indegree[adj] == 0) queue.offer(adj);
}
return count == numCourses;
}
}
time complexity analysis:
O(V+E)
where V is the num of courses(aka. numCourses, nodes), and E is the num of pairs(aka. perequisites.size(), edges). In outer loop, it checks every node only once, in inner loop, it checks every edge only once. It checks every node and edge only once.