![](/img/trans.png)
[英]In a directed, weighted graph, efficiently find the cost of the shortest path between two nodes A and B that traverses through a node X
[英]How can i remove all edges of a specific path(for example the shortest path between two nodes) in a graph?
我想刪除我的網絡圖中的特定路徑,但我不知道該怎么做......例如,我有兩個節點之間的最短路徑作為節點列表(從源節點到目標節點)例如,這是我在節點 A(源節點)和 D(目標節點)之間包含路徑節點的最短路徑:
['A','B','C','D']
有人知道我如何從圖中刪除這條路徑嗎? 我嘗試了很多方法來做到這一點,但他們沒有工作......我已經使用 networkx 庫定義了我的圖表
您可以從創建要刪除的邊列表開始,這里稱為sp
:
sp = []
for i in range(0,len(shortestpath)-1):
sp.append((shortestpath[i],shortestpath[i+1]))
然后使用G.remove_edge
刪除它們:
for u, v in sp:
G.remove_edge(u, v)
這是帶有一個小示例的完整代碼:
G = nx.Graph([(0, 1), (0, 3), (1, 2), (2, 3), (3, 4)])
shortestpath = (3, 0, 1)
sp = []
for i in range(0,len(shortestpath)-1):
sp.append((shortestpath[i],shortestpath[i+1]))
for u, v in sp:
G.remove_edge(u, v)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.