Home Backend Development Python Tutorial Examples to explain Python's solution to the Traveling Salesman Problem (TSP) based on the backtracking subset tree template

Examples to explain Python's solution to the Traveling Salesman Problem (TSP) based on the backtracking subset tree template

Sep 07, 2017 am 10:14 AM
python Backtrace based on

This article mainly introduces Python to solve the traveling salesman problem (TSP) based on the backtracking method subset tree template. It briefly describes the traveling salesman problem and analyzes the related implementation of Python using the backtracking method subset tree template to solve the traveling salesman problem in the form of examples. For steps and operating techniques, friends in need can refer to

This article describes how Python solves the Traveling Salesman Problem (TSP) based on the backtracking subset tree template. Share it with everyone for your reference. The details are as follows:

Problem

The Traveling Salesman Problem (TSP) is the problem of traveling salesmen to Traveling to several cities, the cost between each city is known. In order to save costs, the travel salesman decided to start from the city where he was, travel to each city once and then return to the original city, and asked him what route he should choose to get all the places. The shortest total cost of walking?

Analysis

This problem can be described as follows: G=(V,E) is weighted For a directed graph, find a directed ring containing each node in V, that is, a traveling route that minimizes the sum of the costs of all edges on this directed ring.

The difference between this question and the previous article http://www.jb51.net/article/122933.htm is that this question is a weighted picture. Just a small modification is all it takes.

The length of the solution is fixed n+1.

Every node in the graph has its own adjacent nodes. For a node, all its adjacent nodes constitute the node's state space. When the path reaches this node, its state space is traversed.

In the end, the optimal solution must be found!

Obviously, continue to apply the backtracking method subset tree template! ! !

Code


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

'''旅行商问题(Traveling Salesman Problem,TSP)'''

# 用邻接表表示带权图

n = 5 # 节点数

a,b,c,d,e = range(n) # 节点名称

graph = [

  {b:7, c:6, d:1, e:3},

  {a:7, c:3, d:7, e:8},

  {a:6, b:3, d:12, e:11},

  {a:1, b:7, c:12, e:2},

  {a:3, b:8, c:11, d:2}

]

x = [0]*(n+1) # 一个解(n+1元数组,长度固定)

X = []     # 一组解

best_x = [0]*(n+1) # 已找到的最佳解(路径)

min_cost = 0    # 最小旅费

# 冲突检测

def conflict(k):

  global n,graph,x,best_x,min_cost

  # 第k个节点,是否前面已经走过

  if k < n and x[k] in x[:k]:

    return True

  # 回到出发节点

  if k == n and x[k] != x[0]:

    return True

  # 前面部分解的旅费之和超出已经找到的最小总旅费

  cost = sum([graph[node1][node2] for node1,node2 in zip(x[:k], x[1:k+1])])

  if 0 < min_cost < cost:

    return True

  return False # 无冲突

# 旅行商问题(TSP)

def tsp(k): # 到达(解x的)第k个节点

  global n,a,b,c,d,e,graph,x,X,min_cost,best_x

  if k > n: # 解的长度超出,已走遍n+1个节点 (若不回到出发节点,则 k==n)

    cost = sum([graph[node1][node2] for node1,node2 in zip(x[:-1], x[1:])]) # 计算总旅费

    if min_cost == 0 or cost < min_cost:

      best_x = x[:]

      min_cost = cost

      #print(x)

  else:

    for node in graph[x[k-1]]: # 遍历节点x[k-1]的邻接节点(状态空间)

      x[k] = node

      if not conflict(k): # 剪枝

        tsp(k+1)

# 测试

x[0] = c # 出发节点:路径x的第一个节点(随便哪个)

tsp(1)  # 开始处理解x中的第2个节点

print(best_x)

print(min_cost)

Copy after login

Rendering

The above is the detailed content of Examples to explain Python's solution to the Traveling Salesman Problem (TSP) based on the backtracking subset tree template. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1660
14
PHP Tutorial
1259
29
C# Tutorial
1233
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles