Problem :
https://leetcode.com/problems/course-schedule-ii/
class Solution {
public:
vector<int>vis;
vector<int>vec[5005];
vector<int> ans;
bool dfsAndReturnCycle(int src)
{
if(vis[src] == 1)
return true;
if(vis[src] == 2)
return false;
vis[src] = 1;
for (const auto& nextNode: vec[src])
{
if(dfsAndReturnCycle(nextNode))
return true;
}
vis[src] = 2;
ans.push_back(src);
return false;
}
vector<int> findOrder(int numCourses, vector<vector<int>>& ar) {
int n=ar.size();
for(int i=0;i<n;i++){
int v=ar[i][0];
int u=ar[i][1];
vec[u].push_back(v);
}
int flag=0;
vis = vector<int>(numCourses+2,0);
for(int i=0;i<numCourses;i++)
{
if(vis[i]==0){
if(dfsAndReturnCycle(i))
{
return {};
}
}
}
reverse(ans.begin(),ans.end());
return ans;
}
};