[LeetCode][JavaScript]Course Schedule
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.
- 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.
https://leetcode.com/problems/course-schedule/
选课,[m,n],选m的先决条件是要先选n。
拓扑排序,用DFS实现。
用邻接表建图。循环遍历建立所有节点,再循环所有的边把图建出来。
最后遍历所有的点进行DFS。
两个关键的哈希表:visited和visitedPath。
visited是DFS外层循环用的,访问过的点就不再访问了,节省时间;visitedPath是记录回溯的路径,这东西是本题的关键。
举例来说canFinish(4, [[1,0],[2,0],[3,1],[3,2]]) :
走0 -> 1 -> 3这条路的时候,会访问到3,visited[3]记成true了。
当走0 -> 2 -> 3的时候,如果只是看visited变量,3已经访问过了。
所以需要visitedPath记录当前路径上的点,当一条路走不通回溯的时候,visitedPath也需要回溯。
1 /** 2 * @param {number} numCourses 3 * @param {number[][]} prerequisites 4 * @return {boolean} 5 */ 6 var canFinish = function(numCourses, prerequisites) { 7 var map = {}, visited = {}, visitedPath = {}; 8 //build map 9 for(i = 0; i < numCourses; i++){ 10 map[i] = { index : i, next : [] }; 11 } 12 //add edge 13 for(i = 0; i < prerequisites.length; i++){ 14 map[prerequisites[i][1]].next.push(map[prerequisites[i][0]]); 15 } 16 //bfs 17 for(i = 0; i < numCourses; i++){ 18 if(!visited[i]){ 19 if(!bfs(map[i])){ 20 return false; 21 } 22 } 23 } 24 return true; 25 26 function bfs(node){ 27 visited[node.index] = true; 28 visitedPath[node.index] = true; 29 if(node.next.length > 0){ 30 for(var i = 0; i < node.next.length; i++){ 31 if(visitedPath[node.next[i].index]){ 32 return false; 33 } 34 if(!bfs(map[node.next[i].index])){ 35 return false; 36 } 37 } 38 } 39 visitedPath[node.index] = false; 40 return true; 41 } 42 };