python中networkx包学习——最短路径函数shortest_path及shorest_path_length

来源:互联网 发布:什么软件支持货到付款 编辑:程序博客网 时间:2024/06/03 15:56

函数调用

shortest_path(G, source=None, target=None, weight=None)#寻找最短路径shortest_path_length(G, source=None, target=None, weight=None)#求最短路径长度

参数表

参数 含义 G 一个网络图 source(node, optional) 路径的源点;如果缺省,则视网络中每一个点都为源节点分别计算路径 target(node, optional) 路径终点;如果缺省,则视网络中每一个点为终点计算路径 weight(None or string, optional(default=None)) 如果为None,则每条边权重视为1;如果为字符串,则将它作为边的权重。如果缺省视为权重为1

————————————————————————————————————————————————————————————————————————

例子:

import networkx as nximport pylab import numpy as np#自定义网络row=np.array([0,0,0,1,2,3,6])col=np.array([1,2,3,4,5,6,7])print('生成一个空的有向图')G=nx.DiGraph()print('为这个网络添加节点...')for i in range(0,np.size(col)+1):    G.add_node(i)print('在网络中添加带权中的边...')for i in range(np.size(row)):    G.add_edges_from([(row[i],col[i])])print('给网路设置布局...')pos=nx.shell_layout(G)print('画出网络图像:')nx.draw(G,pos,with_labels=True, node_color='white', edge_color='red', node_size=400, alpha=0.5 )pylab.title('Self_Define Net',fontsize=15)pylab.show()'''shortest_path function'''p=nx.shortest_path(G,source=0,target=7)print('源节点为0,终点为7:', p)distance=nx.shortest_path_length(G,source=0,target=7)print('源节点为0,终点为7,最短距离:', distance)p=nx.shortest_path(G,source=0) # target not specifiedprint('只给定源节点0:', p[7])distance=nx.shortest_path_length(G,source=0) # target not specifiedprint('只给定源节点0, 最短距离:', distance[7])p=nx.shortest_path(G,target=7) # source not specifiedprint('只给定终点7:', p[0])distance=nx.shortest_path_length(G,target=7)# source not specifiedprint('只给定终点7,最短距离:', distance[0])p=nx.shortest_path(G) # source,target not specifiedprint('源节点,终点都为给定:', p[0][7])distance=nx.shortest_path_length(G) # source,target not specifiedprint('源节点,终点都为给定,最短距离:', distance[0][7])

——————————————————————————————————————————————

输出结果

runfile('D:/project/python_instruct/Networkx.py', wdir='D:/project/python_instruct')生成一个空的有向图为这个网络添加节点...在网络中添加带权中的边...给网路设置布局...画出网络图像:源节点为0,终点为7: [0, 3, 6, 7]源节点为0,终点为7,最短距离: 3只给定源节点0: [0, 3, 6, 7]只给定源节点0, 最短距离: 3只给定终点7: [0, 3, 6, 7]只给定终点7,最短距离: 3源节点,终点都为给定: [0, 3, 6, 7]源节点,终点都为给定,最短距离: 3

这里写图片描述

参考

更多详细介绍和案例可参考网站1和2

原创粉丝点击