-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtravellingsalesman.py
More file actions
53 lines (42 loc) · 1.06 KB
/
Copy pathtravellingsalesman.py
File metadata and controls
53 lines (42 loc) · 1.06 KB
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
49
50
51
52
53
from sys import maxsize
v = 4
def travelling_salesman_function(graph, s):
vertex = []
for i in range(v):
if i != s:
vertex.append(i)
min_path = maxsize
while True:
current_cost = 0
k = s
for i in range(len(vertex)):
current_cost += graph[k][vertex[i]]
k = vertex[i]
current_cost += graph[k][s]
min_path = min(min_path, current_cost)
if not next_perm(vertex):
break
return min_path
def next_perm(l):
n = len(l)
i = n-2
while i >= 0 and l[i] > l[i+1]:
i -= 1
if i == -1:
return False
j = i+1
while j < n and l[j] > l[i]:
j += 1
j -= 1
l[i], l[j] = l[j], l[i]
left = i+1
right = n-1
while left < right:
l[left], l[right] = l[right], l[left]
left += 1
right -= 1
return True
graph = [[0,10,15,20], [10,0,35,25], [15,35,0,30], [20,25,30,0]]
s = 0
res = travelling_salesman_function(graph,s)
print(res)