Skip to content

Commit

Permalink
Create CourseSchedule-I.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kshitiz11101 authored May 30, 2024
1 parent 1551da4 commit 540fd06
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions Graphs/CourseSchedule-I.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<int>adj[numCourses];
for(auto i:prerequisites){
adj[i[0]].push_back(i[1]);
}
vector<int>indegree(numCourses,0);
for(int i=0;i<numCourses;i++){
for(auto it:adj[i]){
indegree[it]++;
}
}
queue<int>q;
for(int i=0;i<numCourses;i++){
if(indegree[i]==0){
q.push(i);
}
}
vector<int>topo;
while(!q.empty()){
int node=q.front();
q.pop();
topo.push_back(node);

for(auto it:adj[node]){
indegree[it]--;
if(indegree[it]==0){
q.push(it);
}
}
}

if(topo.size()==numCourses){
return true;
}
return false;
}
};

0 comments on commit 540fd06

Please sign in to comment.