【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

相关推荐
Awesome Baron7 分钟前
《Learning Langchain》阅读笔记8-RAG(4)在vector store中存储embbdings
python·jupyter·chatgpt·langchain·llm
阡之尘埃9 分钟前
Python数据分析案例73——基于多种异常值监测算法探查内幕交易信息
人工智能·python·机器学习·数据分析·异常检测·无监督学习
Yhame.15 分钟前
【使用层次序列构建二叉树(数据结构C)】
c语言·开发语言·数据结构
言之。21 分钟前
【Go语言】RPC 使用指南(初学者版)
开发语言·rpc·golang
雾月5539 分钟前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展
蓝莓味柯基1 小时前
Python3:文件操作
python
投笔丶从戎1 小时前
Kotlin Multiplatform--01:项目结构基础
android·开发语言·kotlin
xiaoh_72 小时前
解决视频处理中的 HEVC 解码错误:Could not find ref with POC xxx【已解决】
python·ffmpeg·音视频
杜小暑2 小时前
动态内存管理
c语言·开发语言·动态内存管理
想不明白的过度思考者2 小时前
Java从入门到“放弃”(精通)之旅——JavaSE终篇(异常)
java·开发语言