Skip to content

Commit 2163c04

Browse files
authored
Create 29 - Course Schedule.cpp
1 parent 68151ce commit 2163c04

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

29 - Course Schedule.cpp

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

0 commit comments

Comments
 (0)