所以,我正在尝试在有向图中使用DFS查找循环。现在,我知道如果一个图的拓扑排序不可能,那么这个图包含一个循环。我为拓扑排序制定了以下算法。我不确定应该在哪里修改这段代码,以便返回true
或false
并检查我的图是否包含循环。以下是我使用的算法:
DFS-Loop (Graph G)
1. Mark all vertices as unexplored.
2. Set label = n // number of vertices
3. For each vertex V (belonging to) G
-- If V not yet explored,
-- DFS (G,V)
4. Set f(V) = current_label // here, f(V) is basically the position of V in the ordering
5. current_label--
Where DFS(G,V) will be something like:
1. Mark V as explored.
2. For every vertex K belonging to Adj.(V)
-- If K is not explored,
-- Call DFS(G,K)
我应该在哪里添加检查是否包含循环的代码?
谢谢!
else if K is "fully explored"
。如果我使用一个包含2个节点和1条边的图,你的算法会失败。它会将其标记为具有循环。 - undefined