python图论包networks(最短路,最小生成树带包)

官方文档:

https://networkx.github.io/documentation/networkx-1.10/reference/algorithms.html

 

最短路和最小生成树:

 

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
#G.add_node(1)                  #添加一个节点1
#G.add_edge(2,3,10)            #添加一条边2-3(隐含着添加了两个节点2、3)
#G.add_edge(3,2)                #对于无向图,边3-2与边2-3被认为是一条边
#G.add_weighted_edges_from([(1,2,8)])
#G.add_weighted_edges_from([(1,3,10)])
#G.add_weighted_edges_from([(2,3,6)])

G.add_edge('A', 'B', weight=4)
G.add_edge('B', 'D', weight=2)
G.add_edge('A', 'C', weight=3)
G.add_edge('C', 'D', weight=5)
G.add_edge('A', 'D', weight=6)
G.add_edge('C', 'F', weight=7)
G.add_edge('A', 'G', weight=1)
G.add_edge('H', 'B', weight=2)
for u,v,d in G.edges(data=True):
    print(u,v,d['weight'])
edge_labels=dict([((u,v,),d['weight']) for u,v,d in G.edges(data=True)])
#fixed_position = {'A':[ 1.,  2.], 
#                  'B': [ 1.,  0.], 
#                  'D': [ 5., 5.], 
#                  'C': [ 0.,6.]}#每个点在坐标轴中的位置
#pos=nx.spring_layout(G,pos = fixed_position)#获取结点的位置,每次点的位置都是随机的
pos = nx.spring_layout(G) #也可以不固定点
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels,font_size=14)#绘制图中边的权重

print(edge_labels)
print("nodes:", G.nodes())      #输出全部的节点: [1, 2, 3]
print("edges:", G.edges())      #输出全部的边:[(2, 3)]
print("number of edges:", G.number_of_edges())   #输出边的数量

nx.draw_networkx(G,pos,node_size=400)
plt.savefig("wuxiangtu.png")
plt.show()


# 生成邻接矩阵
mat = nx.to_numpy_matrix(G)
print(mat)


# 计算两点间的最短路
# dijkstra_path
print('dijkstra方法寻找最短路径:')
path=nx.dijkstra_path(G, source='H', target='F')
print('节点H到F的路径:', path)
print('dijkstra方法寻找最短距离:')
distance=nx.dijkstra_path_length(G, source='H', target='F')
print('节点H到F的距离为:', distance)

# 一点到所有点的最短路
p=nx.shortest_path(G,source='H') # target not specified
d=nx.shortest_path_length(G,source='H')
for node in G.nodes():
    print("H 到",node,"的最短路径为:",p[node])
    print("H 到",node,"的最短距离为:",d[node])
    
# 所有点到一点的最短距离
p=nx.shortest_path(G,target='H') # target not specified
d=nx.shortest_path_length(G,target='H')
for node in G.nodes():
    print(node,"到 H 的最短路径为:",p[node])
    print(node,"到 H 的最短距离为:",d[node])
    
# 任意两点间的最短距离
p=nx.shortest_path_length(G)
p=dict(p)
d=nx.shortest_path_length(G)
d=dict(d)
for node1 in G.nodes():
    for node2 in G.nodes():
        print(node1,"",node2,"的最短距离为:",d[node1][node2])

# 最小生成树
T=nx.minimum_spanning_tree(G) # 边有权重
print(sorted(T.edges(data=True)))

mst=nx.minimum_spanning_edges(G,data=False) # a generator of MST edges
edgelist=list(mst) # make a list of the edges
print(sorted(edgelist))

# 使用A *算法的最短路径和路径长度
p=nx.astar_path(G, source='H', target='F')
print('节点H到F的路径:', path)
d=nx.astar_path_length(G, source='H', target='F')
print('节点H到F的距离为:', distance)

# 找回路
hl = nx.algorithms.find_cycle(G)
print(hl)


# 二分图匹配
G = nx.complete_bipartite_graph(2, 3)
nx.draw_networkx(G)
left, right = nx.bipartite.sets(G)
list(left) #[0, 1]
list(right) #[2, 3, 4]
p = nx.bipartite.maximum_matching(G)
print("输出匹配:",p)


# 最大流
#  graph's maximum flow
# flow is computed between vertex 0 and vertex n-1
# expected input format:
# n
# m
#g = nx.DiGraph()
#n, m = int(input()), int(input())
#for i in range(n):
#    g.add_node(i)
#for _ in range(m):
#    a, b, c = [ int(i) for i in input().split(' ') ]
#    g.add_edge(a, b, capacity=c)
#max_flow = nx.algorithms.flow.maxflow.maximum_flow(g, 0, n-1)[0]
#print(max_flow)
g = nx.DiGraph()
n, m = 4, 5
for i in range(n):
    g.add_node(i)
edge=["0 1 3","1 3 2","0 2 2","2 3 3","0 3 1"]
for x in edge:
    a, b, c = [ int(i) for i in x.split(' ') ]
    g.add_edge(a, b, capacity=c)
nx.draw(g)
max_flow = nx.algorithms.flow.maxflow.maximum_flow(g, 0, n-1)[0]
print(max_flow)

 

posted on 2019-08-20 18:20  蔡军帅  阅读(4796)  评论(0编辑  收藏  举报