A salesman must visit n cities, cities in which n is a complete graph, the salesperson needs just one visit all the cities, and eventually back to the city.
There is a cost travel from city to city, travel expenses and salesman hope at least.
Np problem is the traveling salesman problem, generally you can use backtracking or dynamic programming to solve.
class Solution:
def __init__(self, X, start_node):
self.X = X
self.start_node = start_node
self.array = [[0] * (2 ** (len(self.X) - 1)) for i in range(len(self.X))]
def transfer(self, sets):
su = 0
for s in sets:
su = su + 2 ** (s - 1)
return su
def tsp(self):
s = self.start_node
num = len(self.X)
cities = list(range(num))
cities.pop(cities.index(s))
node = s
return self.solve(node, cities)
def solve(self, node, future_sets):
if len(future_sets) == 0:
return self.X[node][self.start_node]
d = 9999999
distance = []
for i in range(len(future_sets)):
s_i = future_sets[i]
copy = future_sets[:]
copy.pop(i)
distance.append(self.X[node][s_i] + self.solve(s_i, copy))
d = min(distance)
next_one = future_sets[distance.index(d)]
c = self.transfer(future_sets)
self.array[node][c] = next_one
return d
n = int(input())
m = int(input())
D = [[9999999 for j in range(n)] for i in range(n)]
for i in range(m):
a, b, t = list(map(float, input().split()))
a,b = int(a),int(b)
D[a][b] = t
D[b][a] = t
S = Solution(D, 0)
res = int(S.tsp())
if res >= 9999999:
print(-1)
else:
print(res)
Reference:
Comic: What is the traveling salesman problem?
Traveling Salesman Problem Dynamic Programming Solutions (python version)