我试图使用Tarjan算法确定有向图中的周期,该算法在他的研究论文"有向图的基本电路的枚举"来自1972年Septermber。
我使用Python编写算法代码,并使用邻接列表来跟踪节点之间的关系。
所以" G"在下面,节点0指向节点1,节点1指向节点4,6,7 ......等。
G = [[1], [4, 6, 7], [4, 6, 7], [4, 6, 7], [2, 3], [2, 3], [5, 8], [5, 8], [], []]
N = len(G)
points = []
marked_stack = []
marked = [False for x in xrange(0,N)]
g = None
def tarjan(s, v, f):
global g
points.append(v)
marked_stack.append(v)
marked[v] = True
for w in G[v]:
if w < s:
G[v].pop(G[v].index(w))
elif w == s:
print points
f = True
elif marked[w] == False:
if f == g and f == False:
f = False
else:
f = True
tarjan(s, w, g)
g = f
if f == True:
u = marked_stack.pop()
while (u != v):
marked[u] = False
u = marked_stack.pop()
#v is now deleted from mark stacked, and has been called u
#unmark v
marked[u] = False
points.pop(points.index(v))
for i in xrange(0,N):
marked[i] = False
for i in xrange(0,N):
points = []
tarjan(i,i, False)
while (len(marked_stack) > 0):
u = marked_stack.pop()
marked[u] = False
Tarjan的算法检测以下周期:
[2,4]
[2,4,3,6,5]
[2,4,3,7,5]
[2,6,5]
[2,6,5,3,4]
[2,7,5]
[2,7,5,3,4]
[3,7,5]
我还完成了Tiernan的算法,并且(正确地)找到了2个额外的周期:
[3,4]
[3,6,5]
我很感激任何帮助,找出Tarjan跳过这两个周期的原因。我的代码中可能存在问题吗?
答案 0 :(得分:3)
在这些方面:
for w in G[v]:
if w < s:
G[v].pop(G[v].index(w))
您正在遍历列表并从中弹出元素。这会阻止迭代按预期工作。
如果您更改代码以制作列表的副本,则会产生额外的周期:
for w in G[v][:]: