我正在研究python 3和networkx 2.0。为了枚举2个节点之间的所有简单路径,我使用nx.all_simple_paths
。
我的图表是无向多图,nx.MultiGraph
。遗憾的是,router.post('/addsubject', function(req, res, next){
枚举了包含边键值的所有路径。因此,不可能轻易区分包含不同平行边的路径。
nx.all_simple_paths
上述代码段的输出为:(u,v)
edge = [(1,2,1), (1,2,2), (1,2,3), (2,3,1), (2,3,2)]
g = nx.MultiGraph()
g.add_edges_from(edge)
for path in map(nx.utils.pairwise, nx.all_simple_paths(g,1,3)):
print(list(path))
但所需的输出是:(u,v,key)
[(1, 2), (2, 3)]
[(1, 2), (2, 3)]
[(1, 2), (2, 3)]
[(1, 2), (2, 3)]
[(1, 2), (2, 3)]
[(1, 2), (2, 3)]
我想要键值的原因是它会使我的后续计算更有效地映射相应的边缘。
我还尝试在搜索时添加键值,如下所示:
[(1, 2, 1), (2, 3, 1)]
[(1, 2, 1), (2, 3, 2)]
[(1, 2, 2), (2, 3, 1)]
[(1, 2, 2), (2, 3, 2)]
[(1, 2, 3), (2, 3, 1)]
[(1, 2, 3), (2, 3, 2)]
修改后的程序(节点1和3之间)的输出是:
def all_simple_paths(G, source=1, target=3, cutoff=(len(g) - 1)):
if cutoff < 1:
return
visited = []
for src, _, key in G.edges(source, keys=True):
visited.append((src,key))
stack = [((v, key) for u, v, key in G.edges(source, keys=True))]
# print(list(stack))
while stack:
children = stack[-1]
# print('children: ')
child = next(children, None)
# print(child)
if child is None:
# print('pop happened!')
stack.pop()
visited.pop()
elif len(visited) < cutoff:
# print('visited <cutoff: ')
# print(visited)
# print(list(child)[0])
if child[0] == target:
# print('child is target')
print(visited + [target])
yield visited + [target]
elif child not in visited:
# print("child not in visited")
visited.append(child)
# print(visited)
stack.append(((v, k) for u, v, k in G.edges(child, keys=True)))
else: # len(visited) == cutoff:
# print('at cutoff')
count = ([child] + list(children)).count(target)
# print('count: ')
# print(count)
count = 1 # Dynamic count is not working
for i in range(count):
# print(visited + [target])
yield visited + [target]
stack.pop()
visited.pop()
输出仍然不完美。边3的键(参见上面的输出)仍然缺失,len(访问)中的[(1, 1), (2, 1), 3]
[(1, 1), (2, 2), 3]
[(1, 1), (2, 3), 3]
[(1, 2), (2, 1), 3]
[(1, 2), (2, 2), 3]
[(1, 2), (2, 3), 3]
[(1, 3), (2, 1), 3]
[(1, 3), (2, 2), 3]
[(1, 3), (2, 3), 3]
属性== cutoff&#34;不是动态的(默认情况下它返回0)