-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path29 - Course Schedule.cpp
61 lines (48 loc) · 1.68 KB
/
29 - Course Schedule.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
public:
bool cycle_find(vector < vector <int> > &graph, int numCourses){
// Create a vector to store indegrees of all
// vertices. Initialize all indegrees as 0.
vector <int> in_degree(numCourses,0);
for(int i = 0; i<numCourses; i++){
for(int j = 0; j<graph[i].size(); j++){
in_degree[graph[i][j]]++;
}
}
// Create an queue and enqueue all vertices with indegree 0
queue <int> q;
for(int i = 0; i<numCourses; i++){
if(in_degree[i] == 0){
q.push(i);
}
}
// Initialize count of visited vertices
int cnt = 0;
// Create a vector to store result (A topological ordering of the vertices)
vector<int> top_order;
while(!q.empty()){
int temp = q.front();
top_order.push_back(temp);
q.pop();
for(int i = 0; i<graph[temp].size(); i++){
in_degree[graph[temp][i]]--;
if(in_degree[graph[temp][i]] == 0){
q.push(graph[temp][i]);
}
}
cnt++;
}
if(cnt != numCourses){
return 0;
}
return 1;
}
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector < vector <int> > graph(numCourses);
int n = prerequisites.size();
for(int i = 0; i<n; i++){
graph[prerequisites[i][0]].push_back(prerequisites[i][1]);
}
return cycle_find(graph,numCourses);
}
};