【python】使用C-W算法解决TSP问题

提示:以下信息来自chatgpt,以下内容仅作为个人学习记录使用


一、使用C-W算法解决TSP问题

TSP问题指的是旅行商问题(Traveling Salesman Problem),是一个经典的组合优化问题。该问题可以描述为:给定一个包含n个城市的地图,旅行商需要从一个城市出发,依次经过所有的城市并最终回到出发城市。旅行商必须走过所有的城市,且每个城市只能经过一次。旅行商可以自由选择任何一个城市作为起点,问如何规划旅行路线才能使总路程最短

C-W节约算法是一种启发式算法,用于解决旅行商问题(TSP)。它的目标是求出一条尽可能短的哈密顿回路。但是由于C-W算法是一种近似算法,因此不能保证找到TSP问题的最小解,但是对于实际问题,它的解通常非常接近最优解,并且具有良好的时间复杂度。此外,C-W算法也适用于大规模问题,这使得它在实际中非常有用。

二、代码

1.代码

代码如下:

import math
# 计算两个城市之间的距离
def dist(a, b):
    return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)

# 在未访问城市中查找距离当前城市最近的城市
def find_nearest(city, cities, visited):
    nearest_dist = float('inf')
    nearest_city = None
    for c in cities:
        if c not in visited and c != city:
            d = dist(city, c)
            if d < nearest_dist:
                nearest_dist = d
                nearest_city = c
    return nearest_city, nearest_dist

# 计算每对城市之间的节约成本
def find_savings(cities):
    savings = []
    for i in range(len(cities)):
        for j in range(i+1, len(cities)):
            d = dist(cities[i], cities[j])
            savings.append((i, j, d))
    return sorted(savings, key=lambda x: x[2], reverse=True)

# 构建城市之间的最小生成树
def minimum_spanning_tree(cities):
    mst = []
    visited = set([cities[0]])
    while len(visited) < len(cities):
        nearest_dist = float('inf')
        nearest_edge = None
        for v in visited:
            c, d = find_nearest(v, cities, visited)
            if d < nearest_dist:
                nearest_dist = d
                nearest_edge = (v, c)
        mst.append(nearest_edge)
        visited.add(nearest_edge[1])
    return mst

def find_euler_tour(mst):
    tour = []
    stack = [mst[0][0]]
    while len(stack) > 0:
        v = stack[-1]
        for e in mst:
            if e[0] == v and e[1] not in tour:
                tour.append(e[1])
                stack.append(e[1])
                break
            elif e[1] == v and e[0] not in tour:
                tour.append(e[0])
                stack.append(e[0])
                break
        else:
            stack.pop()
    return tour

def euler_to_tsp(euler_tour):
    tsp_path = [euler_tour[0]]
    for i in range(1, len(euler_tour)):
        if euler_tour[i] != tsp_path[-1]:
            tsp_path.append(euler_tour[i])
    tsp_path.append(euler_tour[0])
    return tsp_path

def solve_tsp(cities):
    # 计算节约成本
    savings = find_savings(cities)
    # 构建最小生成树
    mst = minimum_spanning_tree(cities)
    # 找到欧拉回路
    euler_tour = find_euler_tour(mst)
    # 将欧拉回路转换为TSP路径
    tsp_path = euler_to_tsp(euler_tour)
    # 计算TSP路径的总长度
    tsp_length = sum([dist(tsp_path[i], tsp_path[i+1]) for i in range(len(tsp_path)-1)])
    return tsp_path, tsp_length

主函数:

if __name__ == '__main__':
    cities = [(1,1),(1,3),(2,2),(3,1),(3,3)]
    tsp_path, tsp_length=solve_tsp(cities)
    print(f'tsp_path:{tsp_path}')
    print(f'tsp_length:{tsp_length}')

2.输出

以上代码可以直接成功运行,在本地运行以上代码后输出了:

tsp_path:[(2, 2), (1, 1), (1, 3), (3, 1), (3, 3), (2, 2)]
tsp_length:9.656854249492381

3.城市坐标

城市坐标可以自己随意改动,按需改动即可

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
以下是用Python编写狼群算法解决TSP问题的完整代码: ```python import numpy as np import random # 定义城市坐标 CITY_POSITIONS = np.array([[60, 200], [180, 200], [80, 180], [140, 180], [20, 160], [100, 160], [200, 160], [140, 140], [40, 120], [100, 120], [180, 100], [60, 80], [120, 80], [180, 60], [20, 40], [100, 40], [200, 40], [20, 20], [60, 20], [160, 20]]) # 常量定义 ALPHA = 0.5 BETA = 0.8 DELTA = 1 N_POP = 10 N_ITERS = 100 N_CITIES = CITY_POSITIONS.shape[0] DISTANCES = np.zeros((N_CITIES, N_CITIES)) for i in range(N_CITIES): for j in range(i + 1, N_CITIES): DISTANCES[i][j] = np.sqrt(np.sum((CITY_POSITIONS[i] - CITY_POSITIONS[j]) ** 2)) DISTANCES[j][i] = DISTANCES[i][j] # 初始化狼群 class Wolf: def __init__(self): self.position = np.random.permutation(N_CITIES) self.fitness = self.evaluate_fitness() def evaluate_fitness(self): return sum([DISTANCES[self.position[i - 1]][self.position[i]] for i in range(N_CITIES)]) + DISTANCES[self.position[-1]][self.position[0]] wolves = [Wolf() for i in range(N_POP)] # 迭代优化 for i in range(N_ITERS): # 排序 wolves = sorted(wolves, key=lambda x: x.fitness) # 更新最优解 best_wolf = wolves[0] best_fitness = best_wolf.fitness # 更新每只狼的位置 for wolf in wolves: # 狼最优解向量 x1 = best_wolf.position # 狼当前解向量 x2 = wolf.position # 狼随机解向量 x3 = wolves[random.randint(0, N_POP - 1)].position # 狼位置更新 wolf.position = np.array([x2[i] + ALPHA * (x1[i] - x2[i]) + BETA * (x3[i] - x2[i]) for i in range(N_CITIES)]) # 边界处理 wolf.position = np.array([np.clip(wolf.position[i], 0, N_CITIES - 1) for i in range(N_CITIES)]) # 评估适应度 wolf.fitness = wolf.evaluate_fitness() # 挑选最优解 wolves = sorted(wolves, key=lambda x: x.fitness) wolves = wolves[:DELTA] # 输出最优解 print('Iteration:', i, 'Best Fitness:', best_fitness, 'Best Solution:', best_wolf.position) ``` 代码中使用了numpy库进行矩阵计算和边界处理。代码中定义了一个Wolf类,表示狼,其中包含了狼的位置和适应度。首先对狼群进行初始化,然后进行迭代优化。每次迭代,首先对狼群按适应度进行排序,然后更新最优解,再更新每只狼的位置。更新位置时,每只狼会受到最优解向量、当前解向量和随机解向量的影响,其中ALPHA和BETA是控制影响程度的参数。更新位置后,对边界进行处理,再评估适应度。更新完所有狼的位置后,再挑选最优解,删除其他狼,输出最优解。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虫本初阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值