使用NearestNeighbor算法解决TSP问题

最近邻点策略:从任意城市出发,每次在没有到过的城市中选择最近的一个,直到经过了所有的城市,最后回到出发城市。

给定初始的城市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()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值