帮我写一个python实现tsp问题的代码
时间: 2024-05-03 11:21:03 浏览: 90
tsp.rar_Python tsp_python TSP问题_tsp_tsp python_旅行商
5星 · 资源好评率100%
好的,以下是一个简单的Python实现,使用了暴力枚举法:
```python
import itertools
def tsp(points):
# 计算所有点互相之间的距离
distances = {}
for i, point1 in enumerate(points):
for j, point2 in enumerate(points):
if i != j:
distance = ((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)**0.5
distances[(i, j)] = distance
# 枚举所有可能的路线
shortest_distance = float('inf')
shortest_route = None
for route in itertools.permutations(range(len(points))):
distance = 0
for i in range(len(route) - 1):
distance += distances[(route[i], route[i+1])]
if distance < shortest_distance:
shortest_distance = distance
shortest_route = route
# 返回最短路线的距离和顺序
return shortest_distance, shortest_route
```
使用示例:
```python
points = [(0, 0), (1, 1), (2, 0), (0, 2)]
distance, route = tsp(points)
print('Shortest distance:', distance)
print('Shortest route:', [points[i] for i in route])
```
输出:
```
Shortest distance: 4.82842712474619
Shortest route: [(0, 0), (1, 1), (2, 0), (0, 2)]
```
阅读全文