TLE for DFS,getting partially correct answer. Please help!


#1

I have used dfs approach.
below is my code
void sub(vector v,unordered_set &s,const vector<vector >g,int n,bool &f)
{
if(!f && s.find(n)!=s.end())
{
s.erase(n);
v[n]=true;
for(int i=0;i<g[n].size();i++)
{
if(v[g[n][i]])
{
f=true;
return;
}
sub(v,s,g,g[n][i],f);
if(f) return;
}
}
}
int Solution::solve(int A, vector &B, vector &C)
{
bool f=false;
vector v(A+1,false);
vector a;
vector<vector > g(A+1,a);
for(int i=0;i<B.size();i++) g[B[i]].push_back(C[i]);
unordered_set s;
for(int i=1;i<=A;i++) s.insert(i);
while(!s.empty())
{
bool f=false;
auto it=s.begin();
sub(v,s,g,*it,f);
if(f) return 0;
}
return 1;
}
I’m getting partially correct answer as TLE is happening. Please help me rectify the problem.


#2

pass all the vector as a reference , that will help you!


#3

it indeed did, bro thanks!