so, i am following algorithm design but the below algorithm implemented from the book, fails in the following e.g., is there an issue with this algo -
bool directed = true;
bool dfs(int v,
vector<vector<int>>& adjList,
vector<bool>& discovered,
vector<bool>& processed,
vector<int>& parent)
{
bool ans = false;
discovered[v] = true;
for(auto x : adjList[v])
{
if(!discovered[x])
{
parent[x] = v;
ans |= dfs(x, adjList, discovered, processed, parent);
}
else if((!processed[x] && parent[v]!=x) || directed)
{
if(parent[x]!=v)
{
return true;
}
}
}
processed[v] = true;
return ans;
}
This is called using =
for(int i = 0; i < n; ++i)
{
if(!discovered[i])
{
dfs(i, adjList, discovered, processed, parent);
}
}
It fails for this e.g. =
is the algo wrong in the book algorithm design manual - the e.g. above prints it has a cycle?
it fails when it is exploring the edge - 2 -- > 3 at that time, parent[3] = 1 and therefore parent[3] != 2 and it returns true and says it has a cycle.
Full code = https://ideone.com/9o0trZ
