gpt4 book ai didi

Python:NetworkX 查找包含给定节点列表的最短路径

转载 作者:太空宇宙 更新时间:2023-11-03 18:06:06 25 4
gpt4 key购买 nike

我有一个图表

G=nx.Graph()

及其边缘

G.add_edge('a', 'b')
G.add_edge('a', 'e')
G.add_edge('b', 'c')
G.add_edge('c', 'd')
G.add_edge('d', 'e')
G.add_edge('e', 'g')
G.add_edge('g', 'f')
G.add_edge('g', 'h')
G.add_edge('g', 'k')
G.add_edge('h', 'j')
G.add_edge('h', 'i')

现在假设我想获得一条从节点“a”开始并应包含节点['d', 'k']的最短路径所以输出应该是['a', 'b', 'c', 'd', 'e', 'g', 'k']有没有一个networkx函数可以给我这样的输出?

最佳答案

我不知道有哪个库函数只会返回包含多个节点的最短路径。

如果查看起始节点和结束节点之间的每条路径的计算成本不是太高,我会将返回路径列表过滤为仅包含我正在查找的节点的路径。

# A lambda to check if the list of paths includes certain nodes
only_containing_nodes = lambda x: 'd' in x and 'k' in x

# If you want to find the shortest path which includes those nodes this
# will get all the paths and then they can be filtered and ordered by
# their length.
all_simple_paths = nx.all_simple_paths(G, source='a', target='k')

# If you only want shortest paths which include both nodes even if a
# path includes the nodes and is not the shortest.
all_shortest_paths = nx.all_shortest_paths(G, source='a', target='k')

filter(only_containing_nodes, all_simple_paths)
# >>> [['a', 'b', 'c', 'd', 'e', 'g', 'k']]

filter(only_containing_nodes, all_shortest_paths)
# >>> []

希望对您有所帮助。

关于Python:NetworkX 查找包含给定节点列表的最短路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26872592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com