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?
Example 1:
Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: 2, [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should
also have finished course 1. So it is impossible.
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.
- 思路
修读课程,给定多组序列[a, b],表示要学习a课程必须先学习b课程。问是否可以全部修完n门课程?题目链接
拓扑排序。统计每个点(课程)的入度,然后把入度为0的入队。再依次出队,每出队一次课程数减一,然后将该点的后续点入度减一,如果为0则入队。最后课程数为0表示可以全部修完。
补充:当需要输出正确的序列时,可以在每次出队的时候记录该点,最后判断是否能修完,若能的话返回结果
import java.util.LinkedList;
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
// 统计所有点的入度
int[] inDegrees = new int[numCourses];
for(int[] arr : prerequisites){
inDegrees[arr[0]] ++;
}
// 将入度为0的点加入队列
LinkedList<Integer> queue = new LinkedList<Integer>();
for(int i=0; i<numCourses; i++){
if(inDegrees[i] == 0){
queue.add(i);
}
}
// 依次出队消除关系
while( !queue.isEmpty()){
int pre = queue.poll();
numCourses --; // 注意每出队一次节点数减1
for(int[] arr : prerequisites){
if(arr[1] != pre){ // 当起点不是pre时跳过
continue;
}
if(--inDegrees[arr[0]] == 0){ // 入度减1然后判断是否可以入队
queue.add(arr[0]);
}
}
}
return numCourses == 0;
}
}