最近邻点策略:从任意城市出发,每次在没有到过的城市中选择最近的一个,直到经过了所有的城市,最后回到出发城市。
给定初始的城市a,寻找与其邻接的最短距离的城市b,记录二者之间的路径并增加总路径长度;下一次从城市b开始,寻找与b邻接的最短距离的城市,循环查找,直到找到n-1条路径(n为城市个数),最后加上终点回到起点的边即可。
import math
import matplotlib.pyplot as plt
import numpy as np
def compute_distance(a, b):
return np.sqrt(np.sum((a - b) ** 2))
def read_tsp_file(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
coord_section_index = lines.index('NODE_COORD_SECTION\n')
data_lines = lines[coord_section_index + 1:-1]
coordinates = []
for line in data_lines:
parts = line.strip().split()
x, y = float(parts[1]), float(parts[2])
coordinates.append([x, y])
return np.array(coordinates)
def knn_tsp_solver(file_path, coordinates):
num_cities = coordinates.shape[0]
unvisited = set(range(1, num_cities))
current_city = 0
path = [current_city]
while unvisited:
min_dist = math.inf
next_city = None
for city in unvisited:
dist = compute_distance(
coordinates[current_city], coordinates[city])
if dist < min_dist:
min_dist = dist
next_city = city
path.append(next_city)
file = open(file_path, "a")
file.write(str(next_city+1))
file.write('\n')
file.close()
unvisited.remove(next_city)
current_city = next_city
return path
# Read TSP data from file
tsp_file_path = r'image.tsp'
coordinates = read_tsp_file(tsp_file_path)
# Solve TSP using KNN algorithm
path_indices = knn_tsp_solver('ans.txt', coordinates)
# Compute the total distance of the path
total_distance = np.sum(
np.sqrt(np.sum(np.diff(coordinates[path_indices], axis=0) ** 2, axis=1)))
print('Total distance:', total_distance)
# Write solution indices to a text file
# write_solution_indices(solution_indices_file_path, path_indices)
# Plot the TSP solution
plt.scatter(coordinates[:, 0], coordinates[:, 1])
plt.plot(coordinates[path_indices, 0], coordinates[path_indices,
1], marker='o', linestyle='-', color='red')
plt.title('TSP Solution using KNN')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()