【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

相关推荐
竹林8184 分钟前
用Python requests搞定Cookie登录,我绕过了三个大坑才成功
爬虫·python·自动化运维
En^_^Joy4 分钟前
JavaScript入门指南:从零到精通
开发语言·javascript
sali-tec7 分钟前
C# 基于OpenCv的视觉工作流-章35-组件连通
图像处理·人工智能·opencv·算法·计算机视觉
总斯霖13 分钟前
P15445永远在一起!题解(月赛T2)
数据结构·c++·算法·深度优先
Frostnova丶20 分钟前
LeetCode 3296. 使山区高度为零的最少秒数
算法·leetcode
于先生吖20 分钟前
2026 新版 Java 同城上门家政服务系统源码 完整可运营
java·开发语言
MIXLLRED24 分钟前
Python模块详解(一)—— socket 和 threading 模块
开发语言·python·socket·threading
会员源码网25 分钟前
抽象数据类型(ADT):理论与实践的桥梁
算法
csbysj202028 分钟前
桥接模式(Bridge Pattern)
开发语言
Jay-r32 分钟前
OpenClaw养龙虾工具安全风险分析:五大隐患及防护建议引言
网络·python·安全·web安全·ai助手·openclaw