###### 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

2016-11-26 23:47:38

#### [leetcode] 207. Course Schedule 解题报告

2016-02-26 14:10:16

#### leetcode 207: Course Schedule

2015-05-20 05:07:51

#### [leetcode-207]Course Schedule（java）

2015-08-26 15:23:03

#### Leetcode 207 Course Schedule 课程表

2015-08-10 18:05:39

#### leetcode Course Schedule

2015-08-04 11:40:57

#### 【LeetCode】207. Course Schedule

2016-05-30 23:40:09

#### 【LeetCode】Course Schedule 解题报告

2015-05-19 17:05:08

#### 【LeetCode】Course Schedule II 解题报告

2015-05-19 17:13:08

#### leetcode 210: Course Schedule II

2015-05-22 07:15:55

## 不良信息举报

leetcode-207. Course Schedule