Created
July 18, 2020 11:31
-
-
Save praneethreddymallupally/855f628e18f7c3bc1be7199b1f2b32e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { | |
vector<vector<int>> adj(numCourses); | |
vector<int> indegree(numCourses,0),ans; | |
for(auto i:prerequisites) { | |
adj[i[1]].push_back(i[0]); | |
indegree[i[0]]++; | |
} | |
queue<int> q; | |
for(int i=0;i<numCourses;i++){ | |
if(indegree[i]==0){ | |
q.push(i); | |
} | |
} | |
while(!q.empty()){ | |
int num=q.front(); | |
ans.push_back(num); | |
q.pop(); | |
for(auto x:adj[num]){ | |
indegree[x]--; | |
if(indegree[x]==0){ | |
q.push(x); | |
} | |
} | |
} | |
if(ans.size()!=numCourses){ | |
return {}; | |
} | |
return ans; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment