在networkx库中,traveling_salesman_problem()函数已被弃用,可以使用approximation函数中的traveling_salesman_problem_approximation()函数来解决该问题。以下是修改后的代码:

import networkx as nx

# 定义景点距离矩阵
distances = [
    [0, 300, 360, 210, 530, 475, 500],
    [300, 0, 380, 270, 230, 285, 200],
    [360, 380, 0, 510, 230, 665, 490],
    [210, 270, 510, 0, 470, 265, 450],
    [530, 230, 230, 470, 0, 515, 260],
    [475, 285, 665, 265, 515, 0, 460],
    [500, 200, 490, 450, 260, 460, 0]
]

# 创建图
G = nx.Graph()

num_nodes = len(distances)

# 添加节点和边
for i in range(num_nodes):
    G.add_node(i)

for i in range(num_nodes):
    for j in range(num_nodes):
        if i != j:
            G.add_edge(i, j, weight=distances[i][j])

# 定义起点和终点
start_node = 0
end_node = num_nodes - 1

# 寻找从起点到终点,经过所有景点一次的最短路径
shortest_path = nx.approximation.traveling_salesman_problem_approximation(G)

# 计算最短路径长度
path_length = sum(G[shortest_path[i]][shortest_path[i + 1]]['weight'] for i in range(num_nodes - 1))

print("最短路径:", shortest_path)
print("最短路径长度:", path_length)

这样修改后的代码应该能够正常运行并输出最短路径和最短路径长度。

---------------------------------------------------------------------------TypeError Traceback most recent call lastCell In22 line 33 30 end_node = num_nodes - 1

原文地址: https://www.cveoy.top/t/topic/iPHH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录