日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

【Python学习系列二十六】networkx库图最短路径求解

發布時間:2025/4/16 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Python学习系列二十六】networkx库图最短路径求解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

場景:基于python庫networkx來求解圖最短路徑,相關算法基礎參考

http://blog.csdn.net/fjssharpsword/article/details/52931373

http://blog.csdn.net/fjssharpsword/article/details/52953640

可看networkx源碼了解其內部算法用的原理。

代碼:

# -*- coding: utf-8 -*-import networkx as nx import matplotlib.pyplot as plt#讀取文件,獲取節點和邊 f = open("D:\\tmp\\gy_contest_link_top.txt", "r") nodelist=[] edgelist=[] while True: line = f.readline() if line: pass # do something here line=line.strip()node=line.split(';')[0]#獲取圖節點nodelist.append(node)in_nodes=line.split(';')[1].split('#')#獲取圖邊,該節點是終點for ins in range( len(in_nodes) ) :if in_nodes[ins].strip() !='': in_edge=(in_nodes[ins],node)if in_edge not in edgelist:edgelist.append(in_edge)out_nodes=line.split(';')[2].split('#')#獲取圖邊,該節點是起點 for ins in range( len(out_nodes) ) :if out_nodes[ins].strip() !='': out_edge=(node,out_nodes[ins])if out_edge not in edgelist:edgelist.append(out_edge)else: break f.close() del nodelist[0] #刪除表頭生成的節點 del edgelist[0] del edgelist[0] #刪除表頭生成的邊 #print len(nodelist) #圖節點 #print len(edgelist) #邊數#有向圖構建 G=nx.DiGraph() G.add_nodes_from(nodelist) G.add_edges_from(edgelist)#任意兩點間最短路徑 ''' try:n=nx.shortest_path_length(G,1,4)print n except nx.NetworkXNoPath:print 'No path' ''' path=nx.all_pairs_shortest_path(G) #for item in path.items(): # print item print path.popitem()#強聯通和弱聯通 for c in nx.weakly_connected_components(G):#弱聯通print ccon = nx.strongly_connected_components(G)#強聯通 print con print type(con) print list(con)#有向圖繪制 nx.draw_networkx(G, pos=None, arrows=True, with_labels=False)#with_labels=False不帶節點名 #plt.savefig('D:\\tmp\\it.png') plt.show()

總結

以上是生活随笔為你收集整理的【Python学习系列二十六】networkx库图最短路径求解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。