jan*_*vdl 5 python algorithm graph-theory tarjans-algorithm
我试图使用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
Run Code Online (Sandbox Code Playgroud)
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跳过这两个周期.我的代码中可能存在问题吗?
在这些行中:
for w in G[v]:
if w < s:
G[v].pop(G[v].index(w))
Run Code Online (Sandbox Code Playgroud)
您正在遍历列表并从中弹出元素。这会阻止迭代按预期工作。
如果您更改代码以制作列表的副本,则会产生额外的循环:
for w in G[v][:]:
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
994 次 |
最近记录: |