|
| 1 | +/** |
| 2 | + * res.js |
| 3 | + *@authors Joe Jiang (hijiangtao@gmail.com) |
| 4 | + *@date 2017-04-17 00:09:34 |
| 5 | + * |
| 6 | + * There are a total of n courses you have to take, labeled from 0 to n - 1. |
| 7 | + * |
| 8 | + * 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] |
| 9 | + * |
| 10 | + * Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? |
| 11 | + * |
| 12 | + * For example: |
| 13 | + * |
| 14 | + * 2, [[1,0]] |
| 15 | + * There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. |
| 16 | + * |
| 17 | + * 2, [[1,0],[0,1]] |
| 18 | + * 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. |
| 19 | + * |
| 20 | + *@param {number} numCourses |
| 21 | + *@param {number[][]} prerequisites |
| 22 | + *@return {boolean} |
| 23 | + */ |
| 24 | +letcanFinish=function(numCourses,prerequisites){ |
| 25 | +letprelen=prerequisites.length, |
| 26 | +maxNoCircle=numCourses*(numCourses-1)/2; |
| 27 | +if(!prelen){ |
| 28 | +returntrue; |
| 29 | +}elseif(prelen>maxNoCircle){ |
| 30 | +returnfalse; |
| 31 | +} |
| 32 | + |
| 33 | +letflags=[],// 存储未访问节点 |
| 34 | +nodemarks=newArray(numCourses),// 存储node访问标记 |
| 35 | +edges=newArray(numCourses);// 存储连边信息 |
| 36 | +for(leti=0;i<numCourses;i++){ |
| 37 | +flags.push(i); |
| 38 | +nodemarks[i]=0; |
| 39 | +edges[i]=[]; |
| 40 | +} |
| 41 | + |
| 42 | +for(leti=0;i<prelen;i++){ |
| 43 | +letsource=prerequisites[i][0], |
| 44 | +target=prerequisites[i][1]; |
| 45 | + |
| 46 | +edges[target].push(source); |
| 47 | +} |
| 48 | + |
| 49 | +while(flags.length){ |
| 50 | +letnode=flags[flags.length-1]; |
| 51 | +if(!dfsVisit(node)){ |
| 52 | +returnfalse; |
| 53 | +} |
| 54 | +flags.pop(); |
| 55 | +} |
| 56 | + |
| 57 | +returntrue; |
| 58 | + |
| 59 | +functiondfsVisit(node){ |
| 60 | +if(nodemarks[node]){ |
| 61 | +returnfalse; |
| 62 | +} |
| 63 | + |
| 64 | +if(flags.indexOf(node)!==-1){ |
| 65 | +nodemarks[node]=1; |
| 66 | +letelen=edges[node].length; |
| 67 | +for(leti=0;i<elen;i++){ |
| 68 | +if(!dfsVisit(edges[node][i])){ |
| 69 | +returnfalse; |
| 70 | +} |
| 71 | +} |
| 72 | +nodemarks[node]=0; |
| 73 | +} |
| 74 | + |
| 75 | +returntrue; |
| 76 | +} |
| 77 | +}; |