[python] usa el algoritmo CW para resolver el problema TSP

Consejos: La siguiente información es de chatgpt, y el siguiente contenido solo se usa como un registro de estudio personal


1. Usa el algoritmo CW para resolver el problema TSP

El problema TSP se refiere al problema del viajante de comercio, que es un problema clásico de optimización combinatoria. El problema se puede describir como: dado un mapa que contiene n ciudades, el viajante de comercio necesita comenzar desde una ciudad, pasar por todas las ciudades y finalmente regresar a la ciudad de partida. El viajante de comercio debe pasar por todas las ciudades, y cada ciudad solo puede pasar una vez. El viajante de comercio es libre de elegir cualquier ciudad como punto de partida y pregunta cómo planificar la ruta de viaje para que la distancia total sea la más corta.

El algoritmo de ahorro de CW es un algoritmo heurístico para resolver el problema del viajante de comercio (TSP). Su objetivo es encontrar un circuito hamiltoniano lo más corto posible. Pero dado que el algoritmo CW es un algoritmo aproximado, no se garantiza encontrar la solución mínima del problema TSP, pero para problemas prácticos, su solución suele ser muy cercana a la solución óptima y tiene una buena complejidad temporal. Además, el algoritmo CW también es aplicable a problemas de gran escala, lo que lo hace muy útil en la práctica.

Dos, el código

1. Código

el código se muestra a continuación:

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

función principal:

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. Salida

El código anterior se puede ejecutar directamente y con éxito.Después de ejecutar el código anterior localmente, el resultado es:

ruta_tsp:[(2, 2), (1, 1), (1, 3), (3, 1), (3, 3), (2, 2)] longitud_tsp:
9.656854249492381

3. Coordenadas de la ciudad

Las coordenadas de la ciudad se pueden cambiar a voluntad, según sea necesario

Supongo que te gusta

Origin blog.csdn.net/CBCY_csdn/article/details/130393559
Recomendado
Clasificación