繁体   English   中英

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

[英]Python: NetworkX Finding shortest path which contains given list of nodes

我有一个图

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)
# >>> []

希望对您有所帮助。

您可以使用shortest_path获取所有最短路径,然后通过验证它是否是子列表来比较包含['d', 'k']的路径。

pathList= [p for p in nx.shortest_path(G,source='a')] #Target not specified 
l=['d', 'k']
def isSubList(G,l):
    return all(True if x in G else False for x in l )

res= [x for x in pathList if  isSubList(x,l)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM