【引用】willshy
發表於:2007-10-24 15:29:189樓 得分:1
無向圖的深度遍歷中,訪問到已訪問過的節點,可以得出 “存在環” 的結論;但在有向圖中並不是這樣。
我把我的算法詳細說下,先建立一個頂點顏色表C[N]
0 白色,未被訪問過的節點標白色
-1 灰色,已經被訪問過一次的節點標灰色
1 黑色,當該節點的所有後代都被訪問過標黑色
仍然是按圖的節點深度遍歷,訪問到V時,V若被訪問過,那麼有2種狀態:
C[V]=-1,程序跳出,存在環
C[V]=1,程序繼續,這不是環
時間複雜度O(n+e)
參考了一下 willshy 回帖,直接試着寫了一段代碼實現,不知道是否考慮周全,請批評指正。
template<class NameType,class DistType>
int Graph<NameType,DistType> ::DFS(int v,int visited[])
{
//cout<<GetValue(v)<<' '; // GetValue() please add
visited[v]=-1;
int w=GetFirstNeighbor(v);
while(w!=-1)
{
if(visited[w]==0)
{
DFS(w,visited);
visited[w]=1;
}
else if (visited[w]==-1) {
cout<<"graph must be acyclic";
return 0;
}
w = GetNextNeighbor(v,w);
}
return 1;
}