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

时间:2014-11-11 19:08:40

标签: python graph networkx

我有图表

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函数可以给我这样的输出?

2 个答案:

答案 0 :(得分:1)

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

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

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

我希望有所帮助。

答案 1 :(得分:0)

您可以使用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)]