【python】TSP不同算法对比

python 复制代码
import matplotlib.pyplot as plt
import networkx as nx
import networkx.algorithms.approximation as nx_app
import math

G = nx.random_geometric_graph(20, radius=0.4, seed=3)
pos = nx.get_node_attributes(G, "pos")

# Depot should be at (0,0)
pos[0] = (0.5, 0.5)

H = G.copy()


# Calculating the distances between the nodes as edge's weight.
for i in range(len(pos)):
    for j in range(i + 1, len(pos)):
        dist = math.hypot(pos[i][0] - pos[j][0], pos[i][1] - pos[j][1])
        dist = dist
        G.add_edge(i, j, weight=dist)

#cycle = nx_app.christofides(G, weight="weight")
cycle = nx_app.greedy_tsp(G)


edge_list = list(nx.utils.pairwise(cycle))


plt.figure(figsize=(8,8))
# Draw closest edges on each node only
nx.draw_networkx_edges(H, pos, edge_color="blue", width=0.5)

# Draw the route
nx.draw_networkx(
    G,
    pos,
    with_labels=True,
    edgelist=edge_list,
    edge_color="red",
    node_size=200,
    width=3,
)

print("The route of the traveller is:", cycle)
plt.show()

christofides:

greedy:

参考资料:

https://networkx.org/documentation/stable/auto_examples/drawing/plot_tsp.html

https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.approximation.traveling_salesman.greedy_tsp.html#networkx.algorithms.approximation.traveling_salesman.greedy_tsp

https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.approximation.traveling_salesman.christofides.html#networkx.algorithms.approximation.traveling_salesman.christofides

相关推荐
胡志辉5 小时前
贪心算法最坑的地方:每一步都看起来很对,最后还是错了
算法
代码北人生5 小时前
GitHub 日榜第一、月下载 110 万:supervision 出现之前,写计算机视觉代码是什么感觉
算法·claude
techdashen5 小时前
Rust 社区在 4 月做了什么:项目管理月报解读
开发语言·rust·mfc
南宫萧幕5 小时前
HEV能量管理策略 Simulink 实战:从零搭建 Rule-based 与 A-ECMS 对比模型及排错指南
人工智能·算法·matlab·simulink·控制
十五年专注C++开发5 小时前
QFluentKit: 一个基于 Qt Widgets 的 Fluent Design 风格 UI 组件库
开发语言·c++·qt·ui·qfluentkit
lly2024065 小时前
PHP JSON 使用指南
开发语言
大飞记Python5 小时前
从“驱动地狱”到一行代码:WebDriverManager使用手记(附模板)
python·测试
沐知全栈开发5 小时前
jQuery 尺寸
开发语言
Byte Wizard5 小时前
C语言指针深入浅出5
c语言·开发语言
Cloud_Shy6185 小时前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第九章 Excel 自动化 上篇)
python·数据分析·excel·numpy·pandas