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

函数调用

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 nx
import 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 specified
print('只给定源节点0:', p[7])
distance=nx.shortest_path_length(G,source=0) # target not specified
print('只给定源节点0, 最短距离:', distance[7])

p=nx.shortest_path(G,target=7) # source not specified
print('只给定终点7:', p[0])
distance=nx.shortest_path_length(G,target=7)# source not specified
print('只给定终点7,最短距离:', distance[0])

p=nx.shortest_path(G) # source,target not specified
print('源节点,终点都为给定:', p[0][7])
distance=nx.shortest_path_length(G) # source,target not specified
print('源节点,终点都为给定,最短距离:', 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

这里写图片描述

参考

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

  • 6
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值