【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

相关推荐
Jonathan Star4 分钟前
在 JavaScript 中, `Map` 和 `Object` 都可用于存储键值对,但设计目标、特性和适用场景有显著差异。
开发语言·javascript·ecmascript
lly2024065 分钟前
Font Awesome 音/视频图标
开发语言
麦烤楽鸡翅6 分钟前
【模板】二维前缀和 (牛客)
java·c++·算法·秋招·春招·二维前缀和·面试算法题
ashuicoder7 分钟前
Python 函数传参与 JavaScript 对比
python
kyle-fang14 分钟前
pytorch-张量
人工智能·pytorch·python
PKNLP19 分钟前
11.大模型Agent应用
python·agent·pip
woshihonghonga22 分钟前
Dropout提升模型泛化能力【动手学深度学习:PyTorch版 4.6 暂退法】
人工智能·pytorch·python·深度学习·机器学习
java1234_小锋25 分钟前
PyTorch2 Python深度学习 - 循环神经网络(RNN)实例
python·rnn·深度学习·pytorch2
froginwe1127 分钟前
MongoDB 查询分析
开发语言
Danceful_YJ28 分钟前
28. 门控循环单元(GRU)的实现
pytorch·python·深度学习