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:
- 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.
- Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
- Topological sort could also be done via BFS.
這道題就是說有一堆課程,有的課程有先修課程,比如說修A之前要修B,然後讓你判斷,能不能修完這些課程。下面的note是說,給你的先修課程是以邊列表呈現的,而不是鄰接矩陣,我們可以注意到題目給我們的是一個二維數組,也就是說[[1,0]],表示的是修1之前要修0。
這道題是典型的拓撲排序。原理也很簡單,在一個有向圖中,每次找到一個沒有前驅節點的節點(也就是入度爲0的節點),然後把它指向其他節點的邊都去掉,重複這個過程(BFS),直到所有節點已被找到,或者沒有符合條件的節點(如果圖中有環存在)。這些下面的提示其實也告訴你了。DFS或者BFS都可以。DFS代碼如下:
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
courses.get(prereq[i][1]).add(prereq[i][0]);
}
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;
}
}
這段代碼並不是我寫的,而是discuss上找到的一個非常高效的算法。我自己寫的BFS只打敗了70,這個打敗了95,所以就不獻醜了。