detecting cycle in the undirected graph(dfs,cpp))
detecting cycle in the undirected graph(dfs,cpp))
==================================================
bool dfs(vector<vector<int>> g,int s,int par)
{
visited[s]=1;
for(int i=0;i<g[s].size();i++)
{
if(visited[g[s][i]]==0)
{
par=s;
if(dfs(g,g[s][i],par))
return true;
}
else
{
if(g[s][i]!=par)
return true;
}
}
return false;
}
///////////////////////////////////////////////////////////////
//// Returns true if the graph contains a cycle, else false. //
///////////////////////////////////////////////////////////////
bool isCyclic(vector<vector<int>>g)
{
for (int i = 0; i < g.size(); i++)
visited[i] = false;
for (int u = 0; u < g.size(); u++)
if (!visited[u])
if (dfs(g,u, -1))
return true;
return false;
}
Comments
Post a Comment