【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

相关推荐
ejinxian9 小时前
2026 年 Java 开发计划-Oracle公布
java·开发语言·java 开发计划
Sylvia-girl9 小时前
Java之日志框架
java·开发语言
永远都不秃头的程序员(互关)9 小时前
【K-Means深度探索(三)】告别“初始陷阱”:K-Means++优化质心初始化全解析!
算法·机器学习·kmeans
oioihoii9 小时前
QT跨平台一次编写,处处编译
开发语言·qt
edisao9 小时前
四。SpaceX、网络化与未来的跨越:低成本、高频次的真正威胁
大数据·开发语言·人工智能·科技·php
程序员-King.9 小时前
day136—快慢指针—重排链表(LeetCode-143)
算法·leetcode·链表·快慢指针
万行9 小时前
差速两轮机器人位移与航向角增量计算
人工智能·python·算法·机器人
qq_336313939 小时前
java基础-多线程练习
java·开发语言·算法
wjs20249 小时前
《jEasyUI 树形网格添加分页》
开发语言
我是一只小青蛙8889 小时前
C++核心过渡:类与对象精讲
开发语言·c++