简体   繁体   English

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

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

I have a graph 我有一个图

G=nx.Graph()

and its edges 及其边缘

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')

And now suppose I want to get a shortest path which start from node 'a' and should contain nodes ['d', 'k'] so the output should be ['a', 'b', 'c', 'd', 'e', 'g', 'k'] is there a networkx function which can give me such output? 现在,假设我想获得一条最短的路径,该路径从节点'a'开始,并且应包含节点['d', 'k']因此输出应为['a', 'b', 'c', 'd', 'e', 'g', 'k']是否有一个networkx函数可以给我这样的输出?

I don't know of a library function which will only return shortest paths which include multiple nodes. 我不知道仅返回包含多个节点的最短路径的库函数。

If it is not too computationally expensive to look at every path between the start node and end node, I would filter the list of return paths to only those which include the nodes I am looking for. 如果查看起始节点和终止节点之间的每条路径在计算上都不算太昂贵,那么我会将返回路径列表过滤为仅包含那些我正在寻找的节点的返回路径。

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

I hope that helps. 希望对您有所帮助。

You can use shortest_path to get all the shortest paths, then compare what paths contains ['d', 'k'] by verifying if it's a sublist or no. 您可以使用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