寻找两个顶点之间的的最短路径。
如果存在最短路径则返回该路径
如果不存在最短路径则反馈None
但是调用nx.shortest_path_length(G,source=1,target=11)后,如果不存在最短路径,则该行代码会报错。
因此,使用try & except 控制异常。
然后问题就解决了。
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
# nc = 20
# nr = 10
G = nx.Graph()
# E = [('a','b',5.0),('b','c',3.0),('a','c',1.0)]
# G.add_weighted_edges_from(E)
# nx.draw(G)
# plt.show()
Matrix = np.array(
[[0, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 1, 1, 0]])
for i in range(len(Matrix)):
for j in range(len(Matrix)):
if Matrix[i,j] > 0:
G.add_edges_from([(i,j)])
G.add_edge(11,12)
LLL = 0
try:
LLL = nx.shortest_path_length(G,source=1,target=11)
except:
LLL = np.inf
print(LLL)
pos = nx.spring_layout(G)
colors = [1,2,3,4,5,6,7,8,9,10]
nx.draw(G,pos,node_color=colors)
plt.show()