所以,我爲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'函數。 –