1、题目描述
你这个学期必须选修 numCourse 门课程,记为 0 到 numCourse-1 。
在选修某些课程之前需要一些先修课程。 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们:[0,1]
给定课程总量以及它们的先决条件,请你判断是否可能完成所有课程的学习?
示例 1:
输入: 2, [[1,0]]
输出: true
解释: 总共有 2 门课程。学习课程 1 之前,你需要完成课程 0。所以这是可能的。
示例 2:
输入: 2, [[1,0],[0,1]]
输出: false
解释: 总共有 2 门课程。学习课程 1 之前,你需要先完成课程 0;并且学习课程 0 之前,你还应先完成课程 1。这是不可能的。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/course-schedule
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2、算法
class Solution {
List<List<Integer>> graph;
int[] visit;// 1正在遍历;0未遍历;-1已遍历
boolean res=true;
public boolean canFinish(int numCourses, int[][] prerequisites) {
graph=new ArrayList<List<Integer>>();
visit=new int[numCourses];
for(int i=0;i<numCourses;i++){
graph.add(new ArrayList<Integer>());
}
for(int[] tmp:prerequisites){
graph.get(tmp[1]).add(tmp[0]);
}
for(int i=0;i<numCourses&&res;i++){//避免不必要的循环
if(visit[i]==0)dfs(i);//跳过已经遍历的
}
return res;
}
void dfs(int node){
visit[node]=1;
for(int i=0;i<graph.get(node).size();i++){
int tmp=graph.get(node).get(i);
if(visit[tmp]==0){
dfs(tmp);
if(res==false)return;//加快速度
}else if(visit[tmp]==1){
res=false;
return;
}
}
visit[node]=-1;
}
}