给出贪心法求解tsp问题的代码
时间: 2024-01-08 17:03:20 浏览: 35
以下是使用贪心算法求解TSP问题的Python代码:
```python
import numpy as np
def tsp_greedy(distance_matrix):
n = len(distance_matrix)
visited = [False] * n # 记录每个城市是否被访问过
path = [0] * n # 记录访问路径
path[0] = start = np.random.randint(0, n) # 随机选择一个起点
visited[start] = True
for i in range(1, n):
# 找到距离当前城市最近的未访问城市
current_city = path[i-1]
min_distance = float('inf')
next_city = -1
for j in range(n):
if not visited[j] and distance_matrix[current_city][j] < min_distance:
min_distance = distance_matrix[current_city][j]
next_city = j
visited[next_city] = True
path[i] = next_city
# 将最后一个城市与起点相连形成回路
path[n-1] = start
# 计算回路的总长度
total_distance = 0
for i in range(n):
total_distance += distance_matrix[path[i-1]][path[i]]
return path, total_distance
```
其中,`distance_matrix`是一个二维数组,表示各个城市之间的距离。函数返回值为一个元组,包含访问路径和回路的总长度。