【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

相关推荐
网上邻居YY1 分钟前
深度学习DL 之 安装PyTorch·GPU版、CUDA(本人Anaconda、Python、PyCharm已提前安装好)
pytorch·经验分享·python·深度学习·pycharm·学习方法
AI、少年郎2 分钟前
如何用个人电脑快速训练自己的语言模型?MiniMind 全流程实战指南
人工智能·python·神经网络·ai·自然语言处理·大模型·模型训练微调
NULL指向我2 分钟前
信号处理学习笔记6:ADC采样线性处理实测拟合
人工智能·算法·机器学习
王家视频教程图书馆4 分钟前
rust 写gui 程序 最流行的是哪个
开发语言·后端·rust
汽车仪器仪表相关领域5 分钟前
NHXJ-02汽车悬架检验台 实操型实战手册
人工智能·功能测试·测试工具·算法·安全·单元测试·可用性测试
枫叶林FYL5 分钟前
【Python高级工程与架构实战】项目四 现代ETL编排平台:Airflow + dbt + Snowflake 企业级数据管道架构与实现
人工智能·python·架构·etl
源码之屋6 分钟前
计算机毕业设计:Python天气数据采集与可视化分析平台 Django框架 线性回归 数据分析 大数据 机器学习 大模型 气象数据(建议收藏)✅
人工智能·python·深度学习·算法·django·线性回归·课程设计
我爱C编程7 分钟前
【3.2】FFT/IFFT变换的数学原理概述与MATLAB仿真
算法·matlab·fpga·fft·ifft
Wadli7 分钟前
Oncall Agent项目
开发语言