这里使用贪心算法求解TSP问题的python版本
# dist 为距离矩阵,start_index 为起始位置
def tsp_quick(dist: list, start_index: int):
sum_distance, seq_result, n = 0, [start_index, ], len(dist)
for path_index in range(n - 1):
distance_list = dist[start_index]
min_dis = max(distance_list)
for index, distance in enumerate(distance_list):
if (index not in seq_result) and (distance < min_dis):
min_dis = distance
start_index = index
sum_distance += min_dis
seq_result.append(start_index)
return sum_distance,seq_result
#使用方法:
dist = [
[2, 5, 6, 7, 3],
[5, 9, 3, 4, 5],
[6, 3, 7, 2, 6],
[7, 4, 2, 5, 2],
[3, 5, 6, 2, 9],
]
sum_distance,seq_list = tsp_quick2(dist, 3) # dist为距离矩阵,3表示从下标为3开始
#返回sum_distance 即为最短距离
#返回序列 [3,2,1,0,4] 表示 3 -> 2 -> 1 -> 0 -> 4