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 | 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 )
X = []
best_x = [ 0 ] * (n + 1 )
min_cost = 0
def conflict(k):
global n,graph,x,best_x,min_cost
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
def tsp(k):
global n,a,b,c,d,e,graph,x,X,min_cost,best_x
if 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
else :
for node in graph[x[k - 1 ]]:
x[k] = node
if not conflict(k):
tsp(k + 1 )
x[ 0 ] = c
tsp( 1 )
print (best_x)
print (min_cost)
|