题目:
思路:
https://www.jianshu.com/p/25868371ddfc/
代码:
java
public boolean canFinish(int numCourses, int[][] prerequisites) {
// 入度
int[] indegress = new int[numCourses];
// 每个点对应的边,出边
Map<Integer, List<Integer>> adjacency = new HashMap<>();
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < numCourses; i++) {
adjacency.put(i, new ArrayList<>());
}
for (int[] cp : prerequisites) {
indegress[cp[0]]++;
adjacency.get(cp[1]).add(cp[0]);
}
for (int i = 0; i < numCourses; i++) {
if (indegress[i] == 0) {
queue.offer(i);
}
}
// BFS
while (!queue.isEmpty()) {
Integer pre = queue.poll();
numCourses--;
for (int cur : adjacency.get(pre)) {
if (--indegress[cur] == 0) {
queue.offer(cur);
}
}
}
return numCourses == 0;
}