【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

相关推荐
小春学渗透几秒前
Day107:代码审计-PHP模型开发篇&MVC层&RCE执行&文件对比法&1day分析&0day验证
开发语言·安全·web安全·php·mvc
杜杜的man3 分钟前
【go从零单排】迭代器(Iterators)
开发语言·算法·golang
亦世凡华、3 分钟前
【启程Golang之旅】从零开始构建可扩展的微服务架构
开发语言·经验分享·后端·golang
测试界的酸菜鱼18 分钟前
C# NUnit 框架:高效使用指南
开发语言·c#·log4j
GDAL18 分钟前
lua入门教程 :模块和包
开发语言·junit·lua
李老头探索19 分钟前
Java面试之Java中实现多线程有几种方法
java·开发语言·面试
小沈熬夜秃头中୧⍤⃝19 分钟前
【贪心算法】No.1---贪心算法(1)
算法·贪心算法
CSXB9921 分钟前
三十四、Python基础语法(文件操作-上)
开发语言·python·功能测试·测试工具
web Rookie40 分钟前
JS类型检测大全:从零基础到高级应用
开发语言·前端·javascript
很楠不爱1 小时前
Qt——窗口
开发语言·qt