
以下是使用Python語言結合networkx庫來解決最短路徑問題的示例。
- 安裝
networkx庫(如果沒有安裝)- 如果使用
pip,可以在命令行中運行pip install networkx。
- 如果使用
- 示例代碼
import networkx as nx
import matplotlib.pyplot as plt# 創建一個有向圖
G = nx.DiGraph()# 添加節點
G.add_nodes_from([1, 2, 3, 4, 5])# 添加邊及權重
G.add_edge(1, 2, weight = 2)
G.add_edge(1, 3, weight = 1)
G.add_edge(2, 4, weight = 3)
G.add_edge(3, 4, weight = 1)
G.add_edge(3, 5, weight = 4)
G.add_edge(4, 5, weight = 2)# 計算從節點1到節點5的最短路徑
shortest_path = nx.shortest_path(G, source = 1, target = 5, weight='weight')
shortest_length = nx.shortest_path_length(G, source = 1, target = 5, weight='weight')print("最短路徑:", shortest_path)
print("最短路徑長度:", shortest_length)# 繪制圖形(可選)
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos)
plt.show()- 在這個示例中:
- 首先創建了一個有向圖
G。 - 然后添加了節點和邊以及邊的權重。
- 使用
nx.shortest_path函數來計算從指定源節點到目標節點的最短路徑,nx.shortest_path_length函數計算最短路徑的長度。 - 最后,還有一段繪制圖形的代碼(這部分是可選的,如果不需要可視化可以刪除相關代碼)。
- 首先創建了一個有向圖
- 在這個示例中:
這只是一個簡單的示例,對于更復雜的圖結構和不同的應用場景,可能需要對代碼進行調整。
