You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Course Schedule.js
+97
Original file line number
Diff line number
Diff line change
@@ -40,5 +40,102 @@ var canFinish = function(numCourses, prerequisites) {
40
40
varhasCycle=dfs(nodes[i],[]);
41
41
if(hasCycle)returnfalse;
42
42
}
43
+
returntrue;
44
+
};
45
+
46
+
47
+
48
+
// SOLUTION 2
49
+
/**
50
+
There are a total of n courses you have to take, labeled from 0 to n - 1.
51
+
52
+
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]
53
+
54
+
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
55
+
56
+
For example:
57
+
58
+
2, [[1,0]]
59
+
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
60
+
61
+
2, [[1,0],[0,1]]
62
+
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.
63
+
64
+
Note:
65
+
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
66
+
67
+
click to show more hints.
68
+
69
+
Hints:
70
+
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.
71
+
Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
0 commit comments