我一直在研究基于networkx版本的python中的全简单路径算法。目前,我要做的唯一更改是让它获取所有节点的所有路径,而不是在 O(n^2) 双循环内进行。
我相信我已经对主要算法进行了排序,但我不太习惯 Python 列表结构的可变性,我认为这就是算法混乱的原因。
我用 Java 编写了一个类似的程序,所以我知道测试图上应该有多少条路径,但我似乎连数字都无法合理接近。
def _all_simple_paths_graph(DG, cutoff):
uniquePaths = []
nlist = DG.nodes()
for source in nlist:
uniqueTreePaths = []
if cutoff < 1:
return
visited = [source]
stack = [iter(DG[source])]
while stack:
children = stack[-1]
child = next(children, None)
if child is None:
stack.pop()
visited.pop()
elif len(visited) < cutoff:
if child not in visited:
visited.append(child)
stack.append(iter(DG[child]))
if visited not in uniqueTreePaths:
yield visited
uniqueTreePaths.append(visited)
else: #len(visited) == cutoff:
if visited not in uniqueTreePaths:
yield visited + [child]
uniqueTreePaths.append(visited)
stack.pop()
visited.pop()
uniquePaths.extend(uniqueTreePaths)
谁能告诉我哪里出错了?我相信这与visited
应该可变的地方和不应该改变的地方有关。但是,我也可能把基本功能弄错了,我对 Python 还很陌生!