【发布时间】:2021-09-20 04:44:30
【问题描述】:
class Solution
{
public:
//Function to detect cycle in a directed graph.
bool dfs(int V, vector<int> adj[],vector <bool>& isvis,int start,vector<bool>**&**anc)
{
isvis[start]=1;
anc[start]=true;
for(auto nb : adj[start])
{
if(!isvis[nb])
{
if(dfs(V,adj,isvis,nb,anc))
return true;
}
if(anc[nb]==true)
return true;
}
for(int i=0;i<V;i++)
{
cout<<i<<" "<<anc[i]<<endl;
}
anc[start]=false;
return false;
}
bool isCyclic(int V, vector<int> adj[])
{
vector < bool > isvis(V,false);
vector <bool> anc(V,false);
for(int i=0;i<V;i++)
{
if(!isvis[i])
{
if(dfs(V,adj,isvis,i,anc))
return true;
}
}
return false;
}
};
【问题讨论】:
标签: graph depth-first-search cycle