vincentiusyoshuac commited on
Commit
72eae0b
·
verified ·
1 Parent(s): babe0db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -12
app.py CHANGED
@@ -26,24 +26,20 @@ def held_karp_tsp(dist_matrix):
26
  bits |= 1 << bit
27
  for next_city in subset:
28
  prev_bits = bits & ~(1 << next_city)
29
- min_dist = inf
30
- for k in subset:
31
- if k == next_city:
32
- continue
33
- current_dist = memo[(prev_bits, k)] + dist_matrix[k][next_city]
34
- if current_dist < min_dist:
35
- min_dist = current_dist
36
- memo[(bits, next_city)] = min_dist
37
 
38
  # Find optimal tour
39
  bits = (2 ** n - 1) - 1
40
  min_tour_cost = inf
41
  last_city = None
42
  for k in range(1, n):
43
- tour_cost = memo[(bits, k)] + dist_matrix[k][0]
44
- if tour_cost < min_tour_cost:
45
- min_tour_cost = tour_cost
46
- last_city = k
 
47
 
48
  # Backtrack to find the full tour
49
  tour = [0]
@@ -51,6 +47,8 @@ def held_karp_tsp(dist_matrix):
51
  for _ in range(n - 1):
52
  tour.append(last_city)
53
  bits &= ~(1 << last_city)
 
 
54
  next_city = min(
55
  [(memo[(bits, k)] + dist_matrix[k][last_city], k) for k in range(n) if (bits, k) in memo],
56
  key=lambda x: x[0],
 
26
  bits |= 1 << bit
27
  for next_city in subset:
28
  prev_bits = bits & ~(1 << next_city)
29
+ if (prev_bits, next_city) in memo:
30
+ min_dist = memo[(prev_bits, next_city)] + dist_matrix[next_city][0]
31
+ memo[(bits, next_city)] = min_dist
 
 
 
 
 
32
 
33
  # Find optimal tour
34
  bits = (2 ** n - 1) - 1
35
  min_tour_cost = inf
36
  last_city = None
37
  for k in range(1, n):
38
+ if (bits, k) in memo:
39
+ tour_cost = memo[(bits, k)] + dist_matrix[k][0]
40
+ if tour_cost < min_tour_cost:
41
+ min_tour_cost = tour_cost
42
+ last_city = k
43
 
44
  # Backtrack to find the full tour
45
  tour = [0]
 
47
  for _ in range(n - 1):
48
  tour.append(last_city)
49
  bits &= ~(1 << last_city)
50
+ if bits == 0:
51
+ break
52
  next_city = min(
53
  [(memo[(bits, k)] + dist_matrix[k][last_city], k) for k in range(n) if (bits, k) in memo],
54
  key=lambda x: x[0],