所以,我为DFS下面的代码:使用DFS检查无向图中的周期?
void dfs (graph * mygraph, int foo, bool arr[]) // here, foo is the source vertex
{
if (arr[foo] == true)
return;
else
{
cout<<foo<<"\t";
arr[foo] = true;
auto it = mygraph->edges[foo].begin();
while (it != mygraph->edges[foo].end())
{
int k = *it;
if (arr[k] == false)
{
//cout<<k<<"\n";
dfs(mygraph,k,arr);
//cout<<k<<"\t";
}
it++;
}
}
//cout<<"\n";
}
现在,我读了,在一个无向图,如果在DFS,再次回到同一个顶点,有一个周期。因此,我做的是这样的,
bool checkcycle(graph * mygraph, int foo, bool arr[])
{
bool result = false;
if (arr[foo] == true)
{
result = true;
}
else
{
arr[foo] = true;
auto it = mygraph->edges[foo].begin();
while (it != mygraph->edges[foo].end())
{
int k = *it;
result = checkcycle(mygraph,k,arr);
it++;
}
}
return result;
}
但是,即使它们没有循环,我的checkcycle函数也会返回true。这是为什么?我的功能有问题吗?没有执行问题,否则我会调试,但他们似乎在我的逻辑中是错误的。
是否在'dfs'之后调用'checkcycle'?正在做适当的清理? –
不,它们是使用开关盒从主调用的单独函数。它不会在它之后或之前被调用。插入边后,我马上调用'checkcycle'函数。 –