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.


The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.


  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++){
            courses.add(new ArrayList<Integer>());
        //add dependencies
        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(!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;
                    return false;
        //it is totally complete and no cycle found in its depth first traversal
        visited[i] = 2;
        return true;

文章标签: java leetcode 题解
所属专栏: LeetCode题解
想对作者说点什么? 我来说一句



leetcode-207. Course Schedule