簡體   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