当前位置: 首页 > news >正文

【回溯算法】【Python实现】TSP旅行售货员问题

文章目录

    • @[toc]
      • 问题描述
      • 回溯算法
      • `Python`实现
      • 时间复杂性

问题描述

  • 给定一组城市和它们之间的距离矩阵,找到一条距离最短的路径,使得旅行商从一个城市出发,经过所有城市恰好一次,并最终回到出发城市

回溯算法

  • 旅行售货员问题的解空间是一棵排列树

  • i = n i = n i=n时,算法搜索至叶结点,其相应的路径长度为 c d cd cd,如果 c d < b e s t d cd < bestd cd<bestd,则表示当前解优于当前最优解,此时更新 b e s t d bestd bestd

  • i < n i < n i<n时,当前扩展结点位于排列树的第 i i i层,图 G G G中存在从顶点 x [ i ] x[i] x[i]到顶点 x [ i + 1 ] x[i + 1] x[i+1]的边时, x [ 1 : i + 1 ] x[1 : i + 1] x[1:i+1]构成图 G G G的一条路径,且当 x [ 1 : i + 1 ] x[1 : i + 1] x[1:i+1]的路径长度小于当前最优值时算法进入排列树的第 i + 1 i + 1 i+1层,否则将剪去相应的子树


Python实现

import numpy as npdef backtrack_tsp(cities):n = len(cities)visited = [False] * n  # 记录城市是否已经被访问shortest_path = []shortest_distance = float('inf')def distance(city1, city2):x1, y1 = city1x2, y2 = city2return np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)# 创建距离矩阵dist_matrix = np.zeros((n, n))for i in range(n):for j in range(n):dist_matrix[i][j] = distance(cities[i], cities[j])def backtrack(path, distance):nonlocal shortest_path, shortest_distanceif len(path) == n:  # 所有城市都已经访问过distance += dist_matrix[path[-1]][path[0]]  # 回到起点的距离if distance < shortest_distance:  # 更新最短路径和最短距离shortest_path = path[:]shortest_distance = distancereturnlast_city = path[-1] if path else 0  # 上一个访问的城市for next_city in range(n):if not visited[next_city]:visited[next_city] = Truepath.append(next_city)distance += dist_matrix[last_city][next_city]backtrack(path, distance)# 恢复回溯前状态distance -= dist_matrix[last_city][next_city]path.pop()visited[next_city] = False# 开始回溯搜索visited[0] = Truebacktrack([0], 0)return shortest_path, shortest_distancecities = [(0, 0), (1, 5), (2, 3), (5, 2), (6, 4)]
shortest_path, shortest_distance = backtrack_tsp(cities)print(f'最短路径: {shortest_path}')
print(f'最短距离: {shortest_distance}')
最短路径: [0, 2, 1, 4, 3]
最短距离: 18.56187155119086

时间复杂性

  • 回溯算法解TSP问题的时间复杂性为 O ( n ! ) O(n!) O(n!)

http://www.lryc.cn/news/350278.html

相关文章:

  • Java处理xml
  • 软考中级-软件设计师 (十一)标准化和软件知识产权基础知识
  • pytest教程-46-钩子函数-pytest_sessionstart
  • Windows内核函数 - ASCII字符串和宽字符串
  • 从零开始学习MySQL 事务处理
  • 字符数组以及字符串相关的几个函数
  • AOP面向切面编程
  • C# WinForm —— 15 DateTimePicker 介绍
  • SpringBoot中六种批量更新Mysql 方式效率对比
  • 【SpringBoot】SpringBoot整合jasypt进行重要数据加密
  • 【Go语言入门学习笔记】Part1.梦开始的地方
  • 数据特征降维 | 主成分分析(PCA)附Python代码
  • 当服务实例出现故障时,Nacos如何处理?
  • 遥感数据集制作(Potsdam数据集为例):TIF图像转JPG,TIF标签转PNG,图像重叠裁剪
  • 根据web访问日志,封禁请求量异常的IP,如IP在半小 时后恢复正常则解除封禁
  • 2.go语言初始(二)
  • MQTT对比HTTP
  • 暴力数据结构之二叉树(堆的相关知识)
  • 死锁调试技巧:工作线程和用户界面线程
  • 蓝桥杯-外卖店优先级(简单写法)
  • VueRouter使用总结
  • Flink checkpoint 源码分析- Checkpoint snapshot 处理流程
  • Leaflet.canvaslabel在Ajax异步请求时bindPopup无效的解决办法
  • Go 处理错误
  • python读取excel数据写入mysql
  • flutter日期选择器仅选择年、月
  • 素数筛详解c++
  • 【Python超详细的学习笔记】Python超详细的学习笔记,涉及多个领域,是个很不错的笔记
  • TINA 使用教程
  • weblogic 任意文件上传 CVE-2018-2894