给出python代码,使用启发式算法解决一个结点数为50的旅行商问题,最终将路线绘制为动画
时间: 2023-03-07 18:53:33 浏览: 108
旅行商问题主要启发式的 2D/3D 可视化_python_代码_下载
答:import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
from random import randint
import matplotlib.animation as animation
# 创建图
G = nx.Graph()
# 设置节点
G.add_nodes_from(range(50))
# 设置边,节点之间的距离
for i in range(50):
for j in range(50):
if i < j:
G.add_edge(i,j,weight=randint(1,10))
# 使用启发式算法求解旅行商问题
def TSP(G, start):
shortest_path = []
remain_node = list(G.nodes)
remain_node.remove(start)
current_node = start
while remain_node:
next_node = min(remain_node, key=lambda x: G[current_node][x]['weight'])
shortest_path.append([current_node, next_node])
remain_node.remove(next_node)
current_node = next_node
shortest_path.append([current_node, start])
return shortest_path
# 动画可视化
def animate(i):
plt.cla()
x = []
y = []
for n in shortest_path[i]:
x.append(G.nodes[n]['pos'][0])
y.append(G.nodes[n]['pos'][1])
plt.plot(x,y,'r-')
plt.scatter(x,y,s=100,c='b')
plt.text(x[1], y[1], '%d'%(i+1), fontsize=15)
shortest_path = TSP(G, 0)
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)
x = []
y = []
for n in shortest_path:
x.append(G.nodes[n[0]]['pos'][0])
y.append(G.nodes[n[0]]['pos'][1])
plt.plot(x,y)
ani = animation.FuncAnimation(fig, animate,
frames=len(shortest_path), interval=200, repeat=False)
plt.show()
阅读全文