You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.8 KiB

# -*- coding: utf-8 -*-
# Time : 2023/11/3 17:21
# Author : lirunsheng
# User : l'r's
# Software: PyCharm
# File : demo6.py
import sys
import itertools
import numpy as np
def tsp_dp(distances):
n = len(distances)
dp = [[sys.maxsize] * n for _ in range(1 << n)]
dp[1][0] = 0
for mask in range(1, 1 << n):
for current in range(n):
if mask & (1 << current):
for previous in range(n):
if previous != current and mask & (1 << previous):
dp[mask][current] = min(dp[mask][current], dp[mask ^ (1 << current)][previous] + distances[previous][current])
shortest_path = sys.maxsize
end_mask = (1 << n) - 1
last_city = -1
for i in range(1, n):
if shortest_path > dp[end_mask][i] + distances[i][0]:
shortest_path = dp[end_mask][i] + distances[i][0]
last_city = i
path = []
mask = end_mask
while last_city >= 0:
path.append(last_city)
new_mask = mask ^ (1 << last_city)
last_city = -1
for i in range(n):
if new_mask & (1 << i):
if last_city == -1 or dp[mask][last_city] + distances[last_city][i] == dp[mask][i]:
last_city = i
mask = new_mask
path.append(0)
path.reverse()
return shortest_path, path
#
# # 测试代码
# distances = [
# [0, 2, 9, 10],
# [1, 0, 6, 4],
# [15, 7, 0, 8],
# [6, 3, 12, 0]
# ]
# 测试代码
distances = np.array([
[np.inf, 80, 99, np.inf, 64, np.inf],
[80, np.inf, 12, 45, 74, 13],
[99, 12, np.inf, 25, np.inf, 61],
[np.inf, 45, 25, np.inf, 45, 47],
[64, 74, np.inf, 45, np.inf, np.inf],
[np.inf, 13, 61, 47, np.inf, np.inf]
])
shortest_path, path = tsp_dp(distances)
print("最短路径长度为:", shortest_path)
print("最短路径为:", path)