Skip to content

Commit

Permalink
Create CourseSchedule-II.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kshitiz11101 authored May 30, 2024
1 parent 7978ec6 commit 1551da4
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions Graphs/CourseSchedule-II.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class Solution {
public:
vector<int> findOrder(int N, vector<vector<int>>& prerequisites) {
vector<int>adj[N];
for(auto i:prerequisites){
adj[i[1]].push_back(i[0]);
}
vector<int>indegree(N,0);
for(int i=0;i<N;i++){
for(auto it:adj[i]){
indegree[it]++;
}
}
queue<int>q;
for(int i=0;i<N;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()==N){
return topo;
}
return {};
}
};

0 comments on commit 1551da4

Please sign in to comment.