【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

相关推荐
搞不懂语言的程序员6 分钟前
装饰器模式详解
开发语言·python·装饰器模式
mosquito_lover110 分钟前
矿山边坡监测预警系统设计
人工智能·python·深度学习·神经网络·视觉检测
王禄DUT11 分钟前
化学方程式配平 第33次CCF-CSP计算机软件能力认证
开发语言·c++·算法
船长@Quant11 分钟前
PyTorch量化进阶教程:第二章 Transformer 理论详解
pytorch·python·深度学习·transformer·量化交易·sklearn·ta-lib
Yang-Never12 分钟前
Open GL ES ->纹理贴图,顶点坐标和纹理坐标组合到同一个顶点缓冲对象中进行解析
android·java·开发语言·android studio·贴图
wuqingshun31415913 分钟前
蓝桥杯 XYZ
数据结构·c++·算法·职场和发展·蓝桥杯
DreamByte26 分钟前
C++菜鸟教程 - 从入门到精通 第五节
开发语言·c++·算法
南玖yy33 分钟前
数据结构C语言练习(两个队列实现栈)
c语言·数据结构·算法
Ljugg38 分钟前
把doi直接插入word中,然后直接生成参考文献
开发语言·c#·word
长流小哥39 分钟前
可视化开发:用Qt实现Excel级动态柱状图
开发语言·c++·qt·ui