Skip to content

207. Course Schedule

Jacky Zhang edited this page Nov 19, 2016 · 2 revisions

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.

解题思路为有向图G(V,E)的问题。

每一个course都是一个vertex,若一门课是另一门的prerequisite,则它们之间有一条directed edge。 因此这个问题转换为在有向图中找有没有cycle的问题。

解法为:

  1. 采用一个队列queue,放入所有indegree为0的vertices。
  2. 若queue不为空,从其中取一个vertex出来,删去所有以它为端点的edge,并update相应节点的indegree,若有indegree变为0的节点,也放入queue。
  3. 直到queue为空,若还有节点剩余,则说明图中有cycle,不能finish所有course。
public class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[][] graph = new int[numCourses][numCourses];
        int[] inDegree = new int[numCourses];
        for(int i = 0; i < prerequisites.length; i++) {
            int ready = prerequisites[i][0];
            int pre = prerequisites[i][1];
            if(graph[pre][ready] == 0) {
                // avoid duplicates
                inDegree[ready]++;
            }
            graph[pre][ready] = 1;
        }
        int count = 0;
        Queue<Integer> queue = new LinkedList<Integer>();
        for(int i = 0; i < numCourses; i++) {
            if(inDegree[i] == 0) queue.offer(i);
        }
        while(!queue.isEmpty()) {
            int course = queue.poll();
            count++;
            for(int i = 0; i < numCourses; i++) {
                if(graph[course][i] == 1) {
                    if(--inDegree[i] == 0) queue.offer(i);
                }
            }
        }
        return count == numCourses;
    }
}
Clone this wiki locally