【備忘録】networkxでダイクストラ

python3
あくまで備忘録なんで雑に記録します

AtCoderで使えそうなんで、簡単なnetworkxを使って有向グラフ

Graph:グラフ
node:頂点
edge:辺
用語degree:頂点の持つ辺の数(次数)

手順

#networkxでダイクストラ
import networkx as nx

G = nx.DiGraph()#有向グラフ
#G = nx.Graph()#無向グラフ

#頂点・辺(重み)
node_list = [1, 2, 3]
edge_weight_list = [[1, 2, 10], [2, 3, 20], [1, 3, 50]]#重み付きグラフ
#edge_list = [[1, 2], [2, 3], [1, 3]]#重み無しグラフの場合

'''単ノード・単エッジ追加したい場合
G.add_node(Edge1)
G.add_edge(Edge1, Edge2)
'''

#リスト追加
G.add_nodes_from(node_list)#頂点の追加#単品可
G.add_weighted_edges_from(edge_weight_list)#重み付き辺の追加#単品可
#G.add_edges_from(edge_list)#重み無し辺の追加#単品可

#始点・終点
start = 1
end = 3

#完成を構築
nx.draw_networkx(G)

matplotlibのpyplot.show()で可視化

最短の道(パス・距離)や情報の出力

#matplotlibで可視化
import matplotlib.pyplot as plt
plt.show()

shortest_path = nx.dijkstra_path(G, start, end)#最短パス#[1, 2, 3]
shortest_path_weight = nx.dijkstra_path_length(G, start, end)#最短パス長(重)#30

print(nx.info(G))#情報を確認
# Name:
# Type: DiGraph
# Number of nodes: 3
# Number of edges: 3
# Average in degree:   1.0000
# Average out degree:   1.0000

G.number_of_nodes()#ノードの総数
G.nodes()#ノードの要素
G.number_of_edges()#エッジの総数
G.edges()#エッジの要素

コメント

"+r+""+h+""+">"}var c,i=n(45),u=n(74),f=n(64),s=n(53),p=n(76),l=n(41),y=(n=n(52),"prototype"),h="script",v=n("IE_PROTO"),g=function(){try{c=new ActiveXObject("htmlfile")}catch(r){}var r;g="undefined"==typeof document||document.domain&&c?function(r){r.write(a("")),r.close();var t=r.parentWindow.Object;return r=null,t}(c):((r=l("iframe")).style.display="none",p.appendChild(r),r.src=String("javascript:"),(r=r.contentWindow.document).open(),r.write(a("document.F=Object")),r.close(),r.F);for(var t=f.length;t--;)delete g[y][f[t]];return g()};s[v]=!0,t.exports=Object.create||function(t,e){var n;return null!==t?(o[y]=i(t),n=new o,o[y]=null,n[v]=t):n=g(),e===r?n:u.f(n,e)}},function(r,t,e){var n=e(5),o=e(44),a=e(43),c=e(45),i=e(11),u=e(75);t.f=n&&!o?Object.defineProperties:function(r,t){c(r);for(var e,n=i(t),o=u(t),f=o.length,s=0;s=t||56320!=(64512&i(r,e))))return!1}return!0}})},function(r,t,e){var n=e(91),o=String;r.exports=function(r){if("Symbol"===n(r))throw new TypeError("Cannot convert a Symbol value to a string");return o(r)}},function(r,t,e){var n=e(2),o=e(7),a=e(13),c=e(15),i=e(102),u=(e=e(6),Array),f=a("".charAt),s=a("".charCodeAt),p=a([].join),l="".toWellFormed,y=l&&e((function(){return"1"!==o(l,1)}));n({target:"String",proto:!0,forced:y},{toWellFormed:function(){var r=i(c(this));if(y)return o(l,r);for(var t=r.length,e=u(t),n=0;n
タイトルとURLをコピーしました