# leetcode-207. Course Schedule

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?

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

2, [[1,0],[0,1]]

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.

Hints:

1. This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
2. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
3. Topological sort could also be done via BFS.

public class Solution {
public boolean canFinish(int numCourses, int[][] prereq) {
int[] visited = new int[numCourses];

//courses that would have the dependency graph
List<List<Integer>> courses = new ArrayList<List<Integer>>();

for(int i=0;i<numCourses;i++){
}

for(int i=0;i< prereq.length;i++){
// for a course, add all the courses that are dependent on it
}

for(int i=0;i<numCourses;i++){
if(visited[i]==0){
if(!dfs(i,courses,visited)) return false;
}
}
return true;

}

public boolean dfs(int i,List<List<Integer>> courses, int[]visited){
visited[i] = 1;

// these are all the courses which are eligible
//when we take their prerequisite, which is course i
List<Integer> eligibleCourses = courses.get(i);

for(int j=0;j<eligibleCourses.size();j++){
int eligibleCourse = eligibleCourses.get(j);
//it is already visited, during previous dfs call, so its a cycle
if(visited[eligibleCourse] == 1) return false;
if(visited[eligibleCourse] == 2) continue;
if(!dfs(eligibleCourse,courses,visited)){
return false;
}
}

//it is totally complete and no cycle found in its depth first traversal
visited[i] = 2;
return true;

}
}

举报原因： 您举报文章：leetcode-207. Course Schedule 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)